ASP MVC Area


Sponsored Links

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 Galaxies, 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, Galaxies. Underneath the Galaxies, 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 GalaxiesAreaRegistration.cs. This file contains the following:


using System.Web.Mvc;

namespace AreasPractise.Areas.Galaxies
{
    public class GalaxiesAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
        get
        {
            return "Galaxies";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Galaxies_default",
                "Galaxies/{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);
}

So, with a folder called 'Areas' now created at the project root, we have a sub-folder called 'Galaxies'. Inside our Galaxies folder we have Controller, Models and Views and our GalaxiesAreaRegistration.cs file shown above. In our Controllers we create a new Controller called MilkyWayController, and in our Views we create a View called MilkyWay. Inside our MilkyWay View we create an Index.aspx page. The URL required to get to the Areas/Galaxies/Views/MilyWay/Index.aspx is (running on a dynamic port in localhost):


http://localhost:49965/Galaxies/MilkyWay


In order to generate a link with Html.ActionLink to our new area we need to specify the area as a new anonymous object as an additional parameter. The below syntax is in ASP.NET MVC 2:


<%: Html.ActionLink("MilkyWay", "Index", "MilkyWay", new { area = "Galaxies" }, null)%>