Как включить файл .html или .asp, используя бритву? - PullRequest
34 голосов
/ 15 марта 2011

Можно ли использовать серверное включение в движке Razor для включения файлов .html или .asp?У нас есть .html-файл и .asp-файлы, которые содержат меню веб-сайтов, которые используются для всех наших веб-сайтов.В настоящее время мы используем серверное включение для всех наших сайтов, поэтому нам нужно только изменить mensu в одном месте.

У меня есть следующий код в теле моего _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>

Вместо включения содержимого файла, если я делаю источник просмотра, я вижу буквальный текст.

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

Ответы [ 14 ]

1 голос
/ 17 марта 2017

вы можете включить серверный код и файл aspx в файлы .cshtml, как показано ниже, а затем включить классические файлы asp или html.Вот шаги

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

2.InsertASPCodeHelper.aspx

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!--#include VIRTUAL="~/Views/Shared/Header.aspx"-->
Header.aspx
<!--#include file="/header/header.inc"-->
1 голос
/ 15 марта 2011

Почему бы не включить в свою страницу _Layout.cshtml раздел, который позволит вам отображать разделы в зависимости от того, какое меню вы хотите использовать.

_Layout.cshtml

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

Тогда на любой странице, которая использует этот макет, у вас будет что-то вроде этого:

@section BannerContent 
{
  @*Place your ASP.NET and HTML within this section to create/render your menus.*@
}
0 голосов
/ 13 июня 2014

Метод расширения Html.Include (lativeVirtualPath)

Я хотел включить такие файлы для целей документации (поместив содержимое файла в

tag).</p>

<p>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.</p>

<p>The real key to getting this code to work was using the <a href="http://msdn.microsoft.com/en-us/library/System.Web.Hosting.VirtualPathProvider%28v=vs.110%29.aspx" rel="nofollow"><code>VirtualPathUtility</code></a> as well as the <a href="http://msdn.microsoft.com/en-us/library/system.web.webpages.webpagebase%28v=vs.111%29.aspx" rel="nofollow"><code>WebPageBase</code></a>.  Sample:</p>

<pre><code>// 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);
</code>

Полный код HtmlHelperExtension:

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);
    }
}
0 голосов
/ 06 июня 2012

Использование include не является правильным способом использования меню с mvc. Вы должны использовать общий макет и / или частичные представления.

Однако, если по какой-то странной причине вы должны включить html-файл, вот способ сделать это.

Помощники / 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));
        }
    }
}

Добавить новое пространство имен в web.config

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

Использование:

@Html.WebPage("/Content/pages/home.html")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...