ASP MVC Area


Sponsored Links

73058_New Scooba® 230 Floor Washing Robot + Free Shipping!

 

ASP MVC Area

Here we look at the ASP MVC Area.

The ASP.NET MVC Area helps us to organise our folder structure of files, specifically the Models, Controllers and Views. So if you'd like to group certain Models, Views and Controllers into groups, as in parent folders, the ASP.NET MVC Area facility allows us to do this whilst maintaining the functionality of the Models, Views and Controllers.

Add an ASP.NET MVC Area

Right click the project in Visual Studio (2010), and then select Add, then select Area. Type in a name for your Area, I chose MyFirstArea, then click Add. The Area folder structure is created. So that's a folder in the website root folder called Areas, with 1 sub-folder with the name I specified for my Area, MyFirstArea. Underneath the MyFirstArea, are folders for Controller, Models and Views. Views contains a sub-folder called Shared and also contains a web.config, and the Views folder contains a file called MyFirstAreaAreaRegistration.cs. This file contains the following:


using System.Web.Mvc;

namespace MyFirst_MvcApplication.Areas.MyFirstArea
{
    public class MyFirstAreaAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
        {
            return "MyFirstArea";
        }
    }

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

This file includes a URL Route mapping so that URLs of MyFirstArea/Controller/Action/Id will be routed to this area. In the Global.asax.cs file there is a method called RegisterAllAreas which is required in order to have our Area's routing registerd so we can use such URLs.


protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterRoutes(RouteTable.Routes);
}