ASP.NET MVC1 Areas

One of the new features in ASP.NET MVC2 is support for areas – a way to organize large projects and group code for specific sections together. For example, instead of having ~/Controllers/HomeController.cs and all the related views in ~/Views/Home/, you have ~/Areas/Home/Controllers/HomeController.cs and the related views in ~/Areas/Home/Views. This might not seem like a big deal, but the larger your project gets the more you come to appreciate the little things like this.

Note that if you want to use views located in a different root directory than ~/Views, you will need to copy the web.config from ~/Views to the root of your new views folder; if you choose to use ~/Areas, you will need to copy it into here (thanks to Francisco)

While this new feature is part of ASP.NET MVC2, developers using MVC1 are not out of luck; with a little bit of code (most of which has already been written for you) you can achieve the same effect. The first thing you need to do is create the folder structure. Since MVC2 uses the root folder ‘Areas’, I will too. Inside this folder, create a sub-folder for each of your areas; for this example I chose to create a folder for ‘User’ and ‘Admin’. Inside each of your area folders, you will need to create folders for ‘Views’ and ‘Controllers’. Note that you can create a models directory if you want, but you should consider putting your models in a separate solution.

Lets start with the controllers. MVC doesn’t care where you place controllers – they don’t even have to be part of the project (the can be part of a referenced assembly)! One problem you might run into, however, is creating multiple controllers with the same name. For example, both our User and Admin areas will have a HomeController. You should put the controllers in different namespaces, like so:

using System;
using System.Web.Mvc;

namespace Mvc1Areas.Controllers.Admin
{
    public class HomeController : Controller
    {
        public ActionResult Index ()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC on Mono!";
            return View ();
        }
    }
}

Mvc1Areas is the base namespace used in my example solution, Mvc1Areas. All controllers go in Mvc1Areas.Controllers.{AreaName}. Following this pattern, the controller for the User area is in the namespace Mvc1Areas.Controllers.User. When you create your routes, you can tell the MVC framework what namespace to look in; we will take a look at the routing configuration after views.

Now create a new MVC View Page in Areas/User/Views/Home named Index.aspx. Unfortunately, the MVC framework will not find it yet. View files are found by the View Engine, which has a list of search paths it will look in to try and find the requested view. If you use the .NET Reflector to inspect System.Web.Mvc.dll, check out WebFormViewEngine:

base.MasterLocationFormats = new string[] { "~/Views/{1}/{0}.master", "~/Views/Shared/{0}.master" };
base.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.aspx", "~/Views/{1}/{0}.ascx", "~/Views/Shared/{0}.aspx", "~/Views/Shared/{0}.ascx" };

. This is the default list of locations searched. {1} will be replaced by the controller name, and {2} by the action. We need to edit this list to support another parameter {2} which can be filled in with the area. Unfortunately, this turns out to be a bit of work. Fortunately for you, all that work is already done:

using System;
using System.Globalization;
using System.Web.Mvc;
using System.Linq;

namespace Mvc1Areas
{
    public sealed class AreaAwareViewEngine : VirtualPathProviderViewEngine
    {
        private const string _cacheKeyFormat = ":ViewCacheEntry:{0}:{1}:{2}:{3}:{4}:";
        private const string _cacheKeyPrefix_Master = "Master";
        private const string _cacheKeyPrefix_Partial = "Partial";
        private const string _cacheKeyPrefix_View = "View";
        private static readonly string[] _emptyLocations = new string[0];

        public AreaAwareViewEngine()
        {
            MasterLocationFormats = new string[] {
                "~/Areas/{2}/Views/{1}/{0}.master",
                "~/Views/{1}/{0}.master",
                "~/Views/Shared/{0}.master"
            };

            ViewLocationFormats = new string[] {
                "~/Areas/{2}/Views/{1}/{0}.aspx",
                "~/Views/{1}/{0}.aspx",
                "~/Views/Shared/{0}.aspx"
            };

            PartialViewLocationFormats = ViewLocationFormats;
        }

        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            return new WebFormView(partialPath, null);
        }

        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            return new WebFormView(viewPath, masterPath);
        }


        private string CreateCacheKey(string prefix, string name, string controllerName, string area)
        {
            return string.Format(CultureInfo.InvariantCulture, _cacheKeyFormat, new object[] { base.GetType().AssemblyQualifiedName, prefix, name, controllerName, area });
        }


        public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
        {
            string[] strArray;
            if (controllerContext == null) {
                throw new ArgumentNullException("controllerContext");
            }
            if (string.IsNullOrEmpty(partialViewName)) {
                throw new ArgumentException("Value cannot be null or empty.", "partialViewName");
            }

            string requiredString = controllerContext.RouteData.GetRequiredString("controller");
            object area;
            controllerContext.RouteData.Values.TryGetValue("area", out area);

            string str2 = this.GetPath(controllerContext, this.PartialViewLocationFormats, "PartialViewLocationFormats", partialViewName, requiredString, (string)area,  "Partial", useCache, out strArray);
            if (string.IsNullOrEmpty(str2)) {
                return new ViewEngineResult(strArray);
            }
            return new ViewEngineResult(this.CreatePartialView(controllerContext, str2), this);
        }

        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            string[] strArray;
            string[] strArray2;
            if (controllerContext == null) {
                throw new ArgumentNullException("controllerContext");
            }
            if (string.IsNullOrEmpty(viewName)) {
                throw new ArgumentException("Value cannot be null or empty.", "viewName");
            }

            string requiredString = controllerContext.RouteData.GetRequiredString("controller");
            object area;
            controllerContext.RouteData.Values.TryGetValue("area", out area);

            string str2 = this.GetPath(controllerContext, this.ViewLocationFormats, "ViewLocationFormats", viewName, requiredString, (string)area,  "View", useCache, out strArray);
            string str3 = this.GetPath(controllerContext, this.MasterLocationFormats, "MasterLocationFormats", masterName, requiredString, (string)area, "Master", useCache, out strArray2);
            if (!string.IsNullOrEmpty(str2) && (!string.IsNullOrEmpty(str3) || string.IsNullOrEmpty(masterName))) {
                return new ViewEngineResult(this.CreateView(controllerContext, str2, str3), this);
            }
            return new ViewEngineResult(strArray.Union(strArray2));
        }

        private string GetPath(ControllerContext controllerContext, string[] locations, string locationsPropertyName, string name, string controllerName, string areaName, string cacheKeyPrefix, bool useCache, out string[] searchedLocations)
        {
            searchedLocations = _emptyLocations;
            if (string.IsNullOrEmpty(name)) {
                return string.Empty;
            }
            if ((locations == null) || (locations.Length == 0)) {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, "The property '{0}' cannot be null or empty.", new object[] { locationsPropertyName }));
            }
            bool flag = IsSpecificPath(name);
            string key = this.CreateCacheKey(cacheKeyPrefix, name, flag ? string.Empty : controllerName, flag ? string.Empty : areaName);
            if (useCache) {
                string viewLocation = this.ViewLocationCache.GetViewLocation(controllerContext.HttpContext, key);
                if (viewLocation != null) {
                    return viewLocation;
                }
            }
            if (!flag) {
                return this.GetPathFromGeneralName(controllerContext, locations, name, controllerName, areaName, key, ref searchedLocations);
            }
            return this.GetPathFromSpecificName(controllerContext, name, key, ref searchedLocations);
        }

        private string GetPathFromGeneralName(ControllerContext controllerContext, string[] locations, string name, string controllerName, string areaName, string cacheKey, ref string[] searchedLocations)
        {
            string virtualPath = string.Empty;
            searchedLocations = new string[locations.Length];
            for (int i = 0; i < locations.Length; i++) {
                if (string.IsNullOrEmpty(areaName) && locations[i].Contains("{2}")) {
                    continue;
                }

                string str2 = string.Format(CultureInfo.InvariantCulture, locations[i], new object[] { name, controllerName, areaName });
                if (this.FileExists(controllerContext, str2)) {
                    searchedLocations = _emptyLocations;
                    virtualPath = str2;
                this.ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, cacheKey, virtualPath);
                    return virtualPath;
                }
                searchedLocations[i] = str2;
            }
            return virtualPath;
        }

        private string GetPathFromSpecificName(ControllerContext controllerContext, string name, string cacheKey, ref string[] searchedLocations)
        {
            string virtualPath = name;
            if (!this.FileExists(controllerContext, name)) {
                virtualPath = string.Empty;
                searchedLocations = new string[] { name };
            }
            this.ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, cacheKey, virtualPath);
    	    return virtualPath;
        }

        private static bool IsSpecificPath(string name)
        {
            char ch = name[0];
            if (ch != '~') {
                return (ch == '/');
            }
            return true;
        }
    }
}

Notice that we added search locations with a '{2}' placeholder, which is filled in with the area name. Add this file anywhere in the project; I put it in the root Views directory. Note that this is not a stand-alone view engine; it is a wrapper around the default WebForms view engine. Now you need to tell the framework to use this view engine instead of the default one; add the following to the end of your RegisterRoutes function:

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new AreaAwareViewEngine());

This removes the default view engine and adds ours.

So we have our view engine that is aware of our views, but how do we tell it what area to look in? And where do the namespaces for our controllers come into play? Take a look at the following code used to register our routes:

routes.MapRoute ("Admin Default",
                 "Admin/{controller}/{action}/{id}",
	                new { controller = "Home", action = "Index", id = "", area = "Admin" },
	                new[] { "Mvc1Areas.Controllers.Admin" }
);
routes.MapRoute ("Default",
                 "{controller}/{action}/{id}",
	                new { controller = "Home", action = "Index", id = "", area = "User" },
	                new[] { "Mvc1Areas.Controllers.User" }
);

You will notice that we are adding an area property in the third parameter. This property is read by our modified view engine and used to determine where to look. Also notice the fourth parameter, which you might not have had need to use before. This parameter lets you specify a list of namespaces to give higher precedence to when choosing the right controller.

And there you have it! The AreaAwareViewEngine is based on code found on a relevant StackOverflow question, so kudos to Aaronaught for laying the foundation for this. You can download an example project. Please leave a comment with any suggestions, feedback, etc etc. I would love to hear from anyone who finds this useful!

  1. Hi, i used your implementation for a site i have using mvc1. The thing is that now my pages are not able to use ViewPage being T my view model for the page. Instead i have to use just ViewPage and cast the Model to the especific type i have over the page.
    Do you know why this could be happening?
    Thanks in advance

    • I remember running into this issue before using MVC1, but I do not remember if it has to do with the area-aware view engine or a different component I was working on.

      Unfortunately I never found a solution

  2. Yeap, it is like somehow the views located into “Views” folder or any other inside it, could be able of taking the inherits=System.Web.Mvc.ViewPage in a good way. But other pages outside do not use it :(

  3. Ok, Problem resolved.

    You need to copy the web.config placed on the Views folder to the new folder where you want to store your new views.

    :)

Leave a Reply

%d bloggers like this: