C# – specify a custom location to “search for views” in ASP.NET MVC


I have the following layout for my mvc project:

  • /Controllers
    • /Demo
    • /Demo/DemoArea1Controller
    • /Demo/DemoArea2Controller
    • etc…
  • /Views
    • /Demo
    • /Demo/DemoArea1/Index.aspx
    • /Demo/DemoArea2/Index.aspx

However, when I have this for DemoArea1Controller:

public class DemoArea1Controller : Controller
    public ActionResult Index()
        return View();

I get the "The view 'index' or its master could not be found" error, with the usual search locations.

How can I specify that controllers in the "Demo" namespace search in the "Demo" view subfolder?

Best Solution

You can easily extend the WebFormViewEngine to specify all the locations you want to look in:

public class CustomViewEngine : WebFormViewEngine
    public CustomViewEngine()
        var viewLocations =  new[] {  
            // etc

        this.PartialViewLocationFormats = viewLocations;
        this.ViewLocationFormats = viewLocations;

Make sure you remember to register the view engine by modifying the Application_Start method in your Global.asax.cs

protected void Application_Start()
    ViewEngines.Engines.Add(new CustomViewEngine());