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

那年仲夏 提交于 2019-11-30 17:28:09

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!

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.

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