【问题标题】:Is it possible to get template from different directory?是否可以从不同的目录获取模板?
【发布时间】:2015-02-10 15:55:07
【问题描述】:

我在不同的项目中使用相同的 cshtml 文件,因此我希望能够共享同一个目录,即“GeneralTemplates”。所以使用@Html.Partial("GeneralTemplates/_Header") 就像一个魅力。但是@Html.MvcSiteMap().SiteMapPath("GeneralTemplates/_Breadcrumbs") 不起作用,这需要在“DisplayTemplates”目录中,然后@Html.MvcSiteMap().SiteMapPath("_Breadcrumbs") 才有效。

有没有人可以让我将文件放在“GeneralTemplates”目录中?我在想也许我能够获取路径的节点列表,但我找不到它。

【问题讨论】:

    标签: c# asp.net-mvc mvcsitemapprovider


    【解决方案1】:

    这比 MvcSiteMapProvider 更像是一个 MVC 问题,因为 MvcSiteMapProvider 使用的是默认的模板化 HTML 帮助器行为。

    它进行了一些搜索,但我找到了一种方法来覆盖此行为,方法是向默认 MVC 视图搜索位置添加额外的路径: Can I Add to the Display/EditorTemplates Search Paths in ASP.NET MVC 3?

    System.Web.Mvc.RazorViewEngine rve = (RazorViewEngine)ViewEngines.Engines
      .Where(e=>e.GetType()==typeof(RazorViewEngine))
      .FirstOrDefault();
    
    string[] additionalPartialViewLocations = new[] { 
      "~/Views/GeneralTemplates/{0}.cshtml"
    };
    
    if(rve!=null)
    {
      rve.PartialViewLocationFormats = rve.PartialViewLocationFormats
        .Union( additionalPartialViewLocations )
        .ToArray();
    }
    

    我认为不可能从路径中删除 /DisplayTemplates 文件夹,因为这是一种约定(将其与 /EditorTemplates 分开)。所以,你能做的最好的事情就是使用上面的配置创建一个文件夹~/Views/GeneralTemplates/DisplayTemplates/

    请注意,MVC 会在转到 /Views/Shared/DisplayTemplates 之前首先检查与您的视图在同一目录中的 /DisplayTemplates 文件夹,因此您也可以将它们移动到使用其相应 HTML 帮助程序的同一视图目录中。

    我没试过,但指定模板时也可以使用完整的视图路径(即~/Views/GeneralTemplates/SiteMapPathHelperModel.cshtml)。

    @Html.MvcSiteMap().SiteMapPath("~/Views/GeneralTemplates/SiteMapPathHelperModel.cshtml")
    

    重要提示:如果您像这样更改所有模板的位置,您可能需要遍历递归模板并更改其中的所有DisplayFor 位置。 p>

    @model MvcSiteMapProvider.Web.Html.Models.SiteMapPathHelperModel
    @using System.Web.Mvc.Html
    @using System.Linq
    @using MvcSiteMapProvider.Web.Html.Models
    
    @foreach (var node in Model) { 
        @Html.DisplayFor(m => node); @* // <-- Need to add the diplaytemplate here, too *@
    
        if (node != Model.Last()) {
            <text> &gt; </text>
        }
    }
    

    如果其他解决方案不适合您,您可以改为构建非模板化的自定义 HTML 帮助程序来解决此问题。

    【讨论】:

    • 感谢您的回复!我尝试了第一个选项,但没有成功(我的 GeneralTemplates 位于 Views/Shared 文件夹中)。并且使用完整路径也不起作用。所以我要创建自定义 HTML 帮助器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 2010-10-10
    • 2016-10-03
    相关资源
    最近更新 更多