I am only using RazorViewEngine
on one of my ASP.NET MVC 3 applications and I cleared Web Forms view engine out with following code inside Application_Start
method of my Global.asax.cs file
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
I decided to see something solid so that I could be satisfied with this two-line-code-effort and I try to render a partial view which does not exist and I got this result :
The partial view '_ResortMapPartialView' was not found or no view engine supports the searched locations. The following locations were searched: ~/Areas开发者_Go百科/Accommodation/Views/resort/_ResortMapPartialView.cshtml ~/Areas/Accommodation/Views/resort/_ResortMapPartialView.vbhtml ~/Areas/Accommodation/Views/Shared/_ResortMapPartialView.cshtml ~/Areas/Accommodation/Views/Shared/_ResortMapPartialView.vbhtml ~/Views/resort/_ResortMapPartialView.cshtml ~/Views/resort/_ResortMapPartialView.vbhtml ~/Views/Shared/_ResortMapPartialView.cshtml ~/Views/Shared/_ResortMapPartialView.vbhtml
It looks a little better. Now it looks for less items than before. But still the files with .vbhtml
extensions are making me unconformable.
The question is that : How can we get rid of them?
My suggestion would be to override the RazorViewEngine
definitions for the following to only include cshtml
files.
- AreaViewLocationFormats
- AreaMasterLocationFormats
- AreaPartialViewLocationFormats
- ViewLocationFormats
- MasterLocationFormats
- PartialViewLocationFormats
- FileExtensions
An brief example:
public class CSHtmlViewEngine: RazorViewEngine
{
public CSHtmlViewEngine()
{
base.AreaViewLocationFormats=
new string[]
{
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.cshtml"
};
base.AreaPartialViewLocationFormats =
new string[]
{
"~/Areas/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Views/Shared/{0}.cshtml",
};
// All the other LocationFormats listed above will also need to be amended
// Don't forget the FileExtensions array
}
}
See my answer which talks about overriding these values. The same principle applies. You will need to register this modified ViewEngine (CSHtmlViewEngine
) in the ApplicationStart
method
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new CSHtmlViewEngine());
Instead of subclassing the RazorViewEngine, or replacing it outright, 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();
}
精彩评论