Can I Add to the Display/EditorTemplates Search Paths in ASP.NET MVC 3?

两盒软妹~` 提交于 2019-11-30 16:48:23

问题


I have a standard set of templates for my mvc projects which I want to keep as an external folder in my source control (SVN)

This means that I cannot put any project specific files in this folder as it will be committed to the wrong place.. .. and my standard templates need to override the ones that are used by MVC itself so they need to be in the place MVC expects overriding templates (e.g. ~/Views/Shared/EditorTemplates)

So where can I put my project specific ones?

Should I put them in ~/Views/Shared/SiteEditorTemplates, for example, and add the path to the search? How would I do that? Or an other suggestions?

thank you, Ant


回答1:


Ok, got it

The editor code in mvc looks for editors in the PartialViewLocationFormats for the engine adding DisplayTemplates or EditorTemplates to the path.

So, I have created a new path under views ~/Views/Standard/

And plopped my standard stuff in there ~/Views/Standard/EditorTemplates/string.cshtml

Now, register the new path in the engine in global.asax Application_Start

protected void Application_Start() {
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    ViewEngines.Engines.Clear();
    var viewEngine = new RazorViewEngine {
        PartialViewLocationFormats = new[]
        {
            "~/Views/{1}/{0}.cshtml",
            "~/Views/Shared/{0}.cshtml",
            "~/Views/Standard/{0}.cshtml"
        }
    };

    ViewEngines.Engines.Add(viewEngine);
}

Note this will get rid of the webforms view engine and the vb paths, but I don't need them anyway

This allows me to have an external for the ~/Views/Standard in SVN and for the project stuff to override if necessary - rah!




回答2:


Personally I externalize specific templates as a NuGet package and everytime I start a new ASP.NET MVC project I simply import this NuGet package and it deploys the templates at their respective locations (~/Views/Shared/EditorTemplates) in order to override the default ones.




回答3:


Instead of replacing the RazorView engine (as was suggested by Anthony Johnston) you can just alter existing RazorViewEngine's PartialViewLocationFormats property. This code goes in Application_Start:

System.Web.Mvc.RazorViewEngine rve = (RazorViewEngine)ViewEngines.Engines
  .Where(e=>e.GetType()==typeof(RazorViewEngine))
  .FirstOrDefault();

string[] additionalPartialViewLocations = new[] { 
  "~/Views/[YourCustomPathHere]"
};

if(rve!=null)
{
  rve.PartialViewLocationFormats = rve.PartialViewLocationFormats
    .Union( additionalPartialViewLocations )
    .ToArray();
}


来源:https://stackoverflow.com/questions/5581786/can-i-add-to-the-display-editortemplates-search-paths-in-asp-net-mvc-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!