One of the new features that was added to ASP.NET MVC2 was support for areas – a way to organize large projects and group code for specific sections together. This is definitely a welcome addition – the larger a project becomes, the more important good organization is.
While areas are a great organizational tool, they are a new feature in MVC2 – meaning anyone using MVC1 is out of luck. At least until they read this article =) You can easily achieve the same effect using the process outlined here, and it is relatively pain-free. The following example is written with the MonoDevelop IDE, so the exact wording might be slightly different in Visual Studio.
The first thing you need to do is create a folder for you to put areas in. Right-click on your solution, Add → New Folder. Since MVC2 uses the 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’.
When you create controllers, you will need to create each controller inside of its own namespace. This way, you can have controllers with the same name, but different areas. For example, the following is a bare-bones controller used in the Admin area:
-
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}. For example, the controller for the User area is in the namespace Mvc1Areas.Controllers.User. Since it is in a different namespace, there is no problem creating a class named HomeController for the Users area and Admin area.
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 by the action. Unfortunately, this turns out to be a bit of work. Fortunately for you, all that work is already done for you. I present the derived view engine that is area aware:
-
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[] {
-
"~/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<string>(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;
-
}
-
}
-
}
Add this file anywhere in the project; I put it in the root Views directory. 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 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 the namespace for the 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!
