Using Areas in ASP.NET/MVC Projects

What Are Areas?

As your web application grows in size and the number of controllers and views increase, it becomes necessary to structure the solution in a logical way to makes sense of it all. If all of this code is kept in one folder it can become unmaintainable. Areas are a powerful feature in Visual Studio that can separate site modules. For example, I use areas to break out the administrative functions and separate them away from the general public features of a site. You could also separate billing or payment systems into different areas.

Areas are basically projects within your main project structure. They exist with their own controllers and views. Areas are almost independent of your main project so they can be maintained and upgraded separately from the main app. In Visual Studio you can add an area by right-clicking on the project name and selecting Add -> Area.

Area Registration

As you can see from the image above when an area is added it also adds the controller, model, and views folders. This structure separates this code from the main project. A file called “AdminAreaRegistration.cs” (mine is called this because my area is called Admin) is also created. The file contains the code needed to register the Admin Area with the main MVC framework.

namespace AreaDemo.Areas.Admin
{
    public class AdminAreaRegistration : AreaRegistration 
    {
        public override string AreaName 
        {
            get 
            {
                return "Admin";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context) 
        {
            context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

In order to tie this all together,  you also need to add the RegisterAllAreas to the Global.asax file which calls the code to register the area.


namespace AreaDemo
{
  public class MvcApplication : System.Web.HttpApplication
  {
    protected void Application_Start()
    {
      AreaRegistration.RegisterAllAreas();
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
      RouteConfig.RegisterRoutes(RouteTable.Routes);
      BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
  }
}