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
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With