How do you include .html or .asp file using razor?

2019-01-22 06:03发布

问题:

Is it possible to use server side include in Razor view engine to include .html or .asp file? We have an .html file and .asp files that contain website menus that are used for all of our websitse. Currently we use server side include for all of our sites so that we only need to change the mensu in one place.

I have the following code in the body of my _Layout.cshtml

<body>
<!--#include virtual="/serverside/menus/MainMenu.asp" -->   
<!--#include virtual="/serverside/menus/library_menu.asp" -->
<!--#include virtual="/portfolios/serverside/menus/portfolio_buttons_head.html" -->
@RenderBody()
</body>

Instead of including the content of the file, if I do a view source, I see the literal text.

" <!--#include virtual="/serverside/menus/MainMenu.asp" --> 
    <!--#include virtual="/serverside/menus/library_menu.asp" -->
    <!--#include virtual="/portfolios/serverside/menus/portfolio_buttons_head.html" -->"

回答1:

Razor does not support server-side includes. The easiest solution would be copying the menu markup into your _Layout.cshtml page.

If you only needed to include .html files you could probably write a custom function that read the file from disk and wrote the output.

However since you also want to include .asp files (that could contain arbitrary server-side code) the above approach won't work. You would have to have a way to execute the .asp file, capture the generated output, and write it out to the response in your cshtml file.

In this case I would go with the copy+paste approach



回答2:

@Html.Raw(File.ReadAllText(Server.MapPath("~/content/somefile.css")))


回答3:

Try making your html page to a cshtml page and including it with:

@RenderPage("_header.cshtml")


回答4:

Try implementing this HTML helper:

public static IHtmlString ServerSideInclude(this HtmlHelper helper, string serverPath)
{
    var filePath = HttpContext.Current.Server.MapPath(serverPath);

    // load from file
    using (var streamReader = File.OpenText(filePath))
    {
        var markup = streamReader.ReadToEnd();
        return new HtmlString(markup);
    }
}

or:

public static IHtmlString ServerSideInclude(this HtmlHelper helper, string serverPath)
{
    var filePath = HttpContext.Current.Server.MapPath(serverPath);

    var markup = File.ReadAllText(filePath);
    return new HtmlString(markup);
}


回答5:

@RenderPage("PageHeader.cshtml")
<!-- your page body here -->
@RenderPage("PageFooter.cshtml")

This works just fine and can save you a lot of time.



回答6:

Create a HtmlHelper extension method that gets the contents of the files:

public static class HtmlHelpers
{
  public static MvcHtmlString WebPage(this HtmlHelper htmlHelper, string url)
  {
    return MvcHtmlString.Create(new WebClient().DownloadString(url));
  }
}

Usage:

@Html.WebPage("/serverside/menus/MainMenu.asp");


回答7:

Sorry guys for bit old answer but I found some way to attach asp file with razor. Of course you need to do some trick but it works! First of all I created .NET MVC 3 application.

In my _Layout.cshtml I added following line:

@Html.Partial("InsertHelper")

Then I created InsertHelper.aspx in my Shared folder with this content:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<!--#include VIRTUAL="/ViewPage1.aspx"-->

ViewPage1.aspx is locaited in my root directory, and has just simple if to check whether it works:

<%
string dummy;
dummy="nz";
%>

<% if (dummy == "nz") { %>
nz indeed
<% } else { %>
not nz
<% } %>

And it works!

Razor is able to render partials with different ViewEngine, and that's why this example is working.

And one more thing: remember to not add following line in both aspx files:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

You can add it only once! Hope it helps!



回答8:

I had the same issue when I tried to include an .inc file in MVC 4.

To solved this issue, I changed the suffix of the file to .cshtml and I added the following line

@RenderPage("../../Includes/global-banner_v4.cshtml")


回答9:

Just do:

@Html.Partial("_SliderPartial")

while "_SliderPartial" is your "_SliderPartial.cshtml" file and your fine.



回答10:

In my _Layout.cshtml I added following line:

@Html.Partial("InsertHelper")

Then I created InsertHelper.aspx in my Shared folder with this content:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<!--#include VIRTUAL="/ViewPage1.aspx"-->


回答11:

Why not include a section within your _Layout.cshtml page that will allow you to render sections based on what menu you want to use.

_Layout.cshtml

<!-- Some stuff. -->
@RenderSection("BannerContent")
<!-- Some other stuff -->

Then, in any page that uses that layout, you will have something like this:

@section BannerContent 
{
  @*Place your ASP.NET and HTML within this section to create/render your menus.*@
}


回答12:

you can include server side code and aspx file in .cshtml files as below and then inlude classic asp files or html files. Here are the steps

  1. Index.cshtml
@Html.RenderPartial("InsertASPCodeHelper")

2.InsertASPCodeHelper.aspx

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!--#include VIRTUAL="~/Views/Shared/Header.aspx"-->
  1. Header.aspx
<!--#include file="/header/header.inc"-->


回答13:

Using includes is not the correct way to use menus with mvc. You should be using a shared layout and/or partial views.

However if for some odd reason, you must include an html file, here is a way to do it.

Helpers/HtmlHelperExtensions.cs

using System.Web;
using System.Web.Mvc;
using System.Net;

namespace MvcHtmlHelpers
{
    public static class HtmlHelperExtensions
    {
        public static MvcHtmlString WebPage(this HtmlHelper htmlHelper, string serverPath)
        {
            var filePath = HttpContext.Current.Server.MapPath(serverPath);
            return MvcHtmlString.Create(new WebClient().DownloadString(filePath));
        }
    }
}

Add new namespace to web.config

<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="MvcHtmlHelpers"/>
  </namespaces>
</pages>

Usage:

@Html.WebPage("/Content/pages/home.html")


回答14:

Html.Include(relativeVirtualPath) Extension Method

I wanted to include files like this for documentation purposes (putting the contents of a file in a <pre> tag).

To do this I added an HtmlHelperExtension with a method that takes a relative virtual path (doesn't have to be an absolute virtual path) and an optional boolean to indicate whether you wish to html encode the contents, which by default my method does since I'm using it primarily for showing code.

The real key to getting this code to work was using the VirtualPathUtility as well as the WebPageBase. Sample:

// Assume we are dealing with Razor as WebPageBase is the base page for razor.
// Making this assumption we can get the virtual path of the view currently
// executing (will return partial view virtual path or primary view virtual
// path just depending on what is executing).
var virtualDirectory = VirtualPathUtility.GetDirectory(
   ((WebPageBase)htmlHelper.ViewDataContainer).VirtualPath);

Full HtmlHelperExtension Code:

public static class HtmlHelperExtensions
{
    private static readonly IEnumerable<string> IncludeFileSupportedExtensions = new String[]
    {
        ".resource",
        ".cshtml",
        ".vbhtml",
    };

    public static IHtmlString IncludeFile(
       this HtmlHelper htmlHelper, 
       string virtualFilePath, 
       bool htmlEncode = true)
    {
        var virtualDirectory = VirtualPathUtility.GetDirectory(
            ((WebPageBase)htmlHelper.ViewDataContainer).VirtualPath);
        var fullVirtualPath = VirtualPathUtility.Combine(
            virtualDirectory, virtualFilePath);
        var filePath = htmlHelper.ViewContext.HttpContext.Server.MapPath(
            fullVirtualPath);

        if (File.Exists(filePath))
        {
            return GetHtmlString(File.ReadAllText(filePath), htmlEncode);
        }
        foreach (var includeFileExtension in IncludeFileSupportedExtensions)
        {
            var filePathWithExtension = filePath + includeFileExtension;
            if (File.Exists(filePathWithExtension))
            {
                return GetHtmlString(File.ReadAllText(filePathWithExtension), htmlEncode);
            }
        }
        throw new ArgumentException(string.Format(
@"Could not find path for ""{0}"".
Virtual Directory: ""{1}""
Full Virtual Path: ""{2}""
File Path: ""{3}""",
                    virtualFilePath, virtualDirectory, fullVirtualPath, filePath));
    }

    private static IHtmlString GetHtmlString(string str, bool htmlEncode)
    {
        return htmlEncode
            ? new HtmlString(HttpUtility.HtmlEncode(str))
            : new HtmlString(str);
    }
}