2

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!

Dave
  • 1,076
  • 5
  • 15
  • 30
  • Can you show an example of how you're trying to render a partial view? Because I've copied your code in the test project and it seems to be working fine for me. Also the view engine class you've shared here is called `CustomViewEngine` but you're adding `IridiumViewEngine` to engines. Is that your actual code or just a mistake while pasting? – TKharaishvili Oct 25 '16 at 21:12
  • @GwynBleidd Oops, yes the `IridiumViewEngine` was a mistake during copy/paste.. I've updated my post above with the way my partial views are being returned. Thanks! – Dave Oct 25 '16 at 21:26

1 Answers1

1

I think specifying the .chstml extension is the problem, try returning the view without it:

return PartialView("ListUsers", Model);
TKharaishvili
  • 1,997
  • 1
  • 19
  • 30