In a bid to keep my views organised within my new MVC 5 application, I've set up a folder structure as follows:
Views
|-- Account
| |-- Partials
| |-- EditUser.cshtml
| |-- ListUsers.cshtml
| |-- Home.cshtml
|
|-- Admin
|-- Partials
|-- AnotherPartialView.cshtml
Now, I'd like to implement a custom view engine for this so I don't have to keep specifying the full path to the Partials
folder in my main view folders.
I've created a custom view engine like this:
public class CustomViewEngine : RazorViewEngine
{
public CustomViewEngine()
: base()
{
var viewLocations = new[] {
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.cshtml",
"~/Views/{1}/Partials/{0}.cshtml"
};
this.PartialViewLocationFormats = viewLocations;
this.ViewLocationFormats = viewLocations;
}
}
and registered it in Application_Start()
within Global.asax
protected void Application_Start()
{
/* snip */
ViewEngines.Engines.Add(new CustomViewEngine());
}
Edit:
I call the partial views like this:
[HttpGet]
/// http://localhost/Account/ListUsers
/// View is located in ~/Views/Account/Partials/ListUsers.cshtml
public ActionResult ListUsers()
{
/* populate model */
return PartialView("ListUsers.cshtml", Model);
}
My thinking was that if I'm including the controller parameter {1}
followed by the Partials
folder within the view locations, this would stop me having to each Partials
sub folder as a location. This would also mean I can just reference the view by name rather than its full path.
However, I'm still receiving an error that the partial view cannot be found in any of the search locations.
Any help would be appreciated.
Thanks!
I think specifying the .chstml
extension is the problem, try returning the view without it:
return PartialView("ListUsers", Model);