Feel like a geek and get yourself Ema Personal Wiki for Android and Windows

09 March 2010

The easiest way for custom View folders in ASP.NET MVC

To change the directory where ASP.NET MVC looks for the views, create a custom ViewEngine and add this ViewEngine to the ViewEngines collection, replacing the old one.

This CustomLocationViewEngine will replace the default "Views" search location with a custom one:
public class CustomLocationViewEngine : WebFormViewEngine
    private string location;
    public CustomLocationViewEngine(string location)
        this.location = location;

        base.MasterLocationFormats = locationFormatsFrom(base.MasterLocationFormats);
        base.ViewLocationFormats = locationFormatsFrom(base.ViewLocationFormats);
        base.PartialViewLocationFormats = locationFormatsFrom(base.PartialViewLocationFormats);

    private string[] locationFormatsFrom(string[] orgLocationFormats)
        return (from l in orgLocationFormats select l.Replace("Views", location)).ToArray();

Assign a new instance of this class to the collection in global.asax.cs, in Application_Start:
ViewEngines.Engines.Add(new CustomLocationViewEngine("Mvc"));

The reason for me to change the default view directory, is that I don't like the default setup where the Controller, the View and the Model all reside in seperate directories. In large applications it is very inconvenient switching between the three parts of the MVC pattern. I have good experiences with this approach:
Create a directory for each controller and put the Controller, Views and Models there. If the directory gets too large, the Controller is too large.

No comments: