Using Areas in ASP.NET MVC Application

WEBINAR: On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

Introduction

ASP.NET MVC relies on certain folder and class naming conventions to organize models, views and controllers. A large application often consists of functionally independent modules with the result that the main application is essentially a bundle of these sub-applications. In such cases, organizing various models, views and controllers can be tedious. Luckily, ASP.NET MVC allows you to split your application into what is known as Areas. Each area mimics the folder structure and conventions as required by ASP.NET MVC. This article shows you how Areas are used in an ASP.NET MVC application.

What are Areas?

Areas are functionally independent modules of your ASP.NET MVC application that mimic the folder structure and conventions of MVC. Consider the following scenario :

Areas are independent modules of your ASP.NET MVC application
Figure 1: Areas are independent modules of your ASP.NET MVC application

As you can see the main application has three functionally independent modules viz. Blog, Help Desk and Shopping. Without any areas in place, you would have put all the controllers and views in the respective folder of the main application folder. Obviously, you cannot have the same controller name for different modules. For example, you cannot have HomeController for Blog and HomeController for HelpDesk. You either need to put all action methods of both the modules in a single controller or create two controllers with altogether different names (say BlogHomeController and HelpDeskHomeController).

With areas in place, each module replicates the MVC folder structure. For example, each module will have its own Models, Views and Controllers folder. You can then have HomeController class in Blog module as well as HelpDesk module. So, in the above example, essentially you will have four MVC structures - one for the main application and one each for the three modules (Blog, HelpDesk and Shopping).

Adding a New Area

Before you work with areas, create a new ASP.NET MVC application with ASPX view engine. To add a new area right click on the application in the Solution Explorer and select the Add > Area shortcut menu option. Doing so will open "Add Area" dialog as shown below:

Adding a New Area
Figure 2: Adding a New Area

You need to enter the Area Name and click the Add button to create the folder structure for that area. The following figure shows the complete folder structure with three Areas - Blog, HelpDesk and Shopping - added.

Solution Explorer
Figure 3: Solution Explorer

As you can see, the main application has Areas subfolders. Inside the Areas subfolders there is a folder for each area you wish to create (Blog, HelpDesk and Shpping in the above example). Each Areaa subfolder has its own set of MVC folders (Models, Views and Controllers). You can treat each area just like the main application and add models, views and controllers in the respective folders.

Registering Areas with MVC Framework

Simply creating area folder structure is not sufficient, you also need to inform ASP.NET MVC framework about the areas you've added. Luckily, this task is automatically done when you add a new area. Notice the area registration class file that was created under each area folder (BlogAreaRegistration.cs, HelpDeskAreaRegistration.cs, etc.). The area registration file contains a class that inherits from AreaRegistration base class. The HelpDeskAreaRegistration class is shown below :

public class HelpDeskAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "HelpDesk";
        }
    }
 
    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "HelpDesk_default",
            "HelpDesk/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

As you can see the HelpDeskAreaRegistration class overrides AreaName property and the RegisterArea method. The RegisterArea method registers the route information for the newly added area with MVC framework.

You will have one area registration class file for each area. When are the area registration classes used? If you open Global.asax file, you will have the following code in the Application_Start event handler :

protected void Application_Start()
{
 AreaRegistration.RegisterAllAreas(); 
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

As you can see, there is a call to RegisterAllAreas() static method of AreaRegistration class. Calling RegisterAllAreas() method in turn invokes the RegisterArea() method of all the area registration classes found in the application.

Before going ahead, add HomeController to all the areas and the main application, i.e. four controller classes with name HomeController. All the HomeController classes will look like this :

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

Then right click on each Index() action method and add Index view, i.e. total four Index views in their respective folders.

Run the application and try navigating to different areas. The following figure shows a sample run for HelpDesk area. Notice the URL of the area.

Run the Application
Figure 4: Run the Application

Linking Between Two Areas

ASP.NET MVC Views often need to link to some action method residing in controller classes. Unless otherwise specified, action methods and controllers are assumed to be from the current area. In case you wish to link to an action method belonging to some other area, here is how you would do just that:

<h3>You are inside main area. To navigate to some other area please click on the following links</h3>
<%= Html.ActionLink("Main Area", "Index", "Home", new { area = "" }, null)%>
<br /><br />
<%= Html.ActionLink("Blog Area", "Index", "Home", new { area = "Blog" }, null)%>
<br /><br />
<%= Html.ActionLink("Help Desk Area", "Index", "Home", new { area = "HelpDesk" }, null)%>
<br /><br />
<%= Html.ActionLink("Shopping Area", "Index", "Home", new { area = "Shopping" }, null)%>

The above fragment is from the Index view of the main area. It renders four hyperlinks using ActionLink(). Notice the fourth parameter that specifies area name. This parameter governs the area whose action method is being linked to.

Redirecting to an Action Belonging to Another Area

You can also redirect to some action method of a specific area using RedirectToAction() method. Consider the following action method:

public ActionResult Index()
{
    return RedirectToAction("Index", "Home", new { Area = "HelpDesk" });
}

As you can see, the Index() action method of the main area redirects the control to Index() action method of the HelpDesk area.

Summary

ASP.NET MVC allows you to organize your application into areas. Each area replicates the MVC structure and can be treated as independent as far as models, views and controllers are concerned. An area is registered with MVC framework using an area registration class and RegisterAllAreas() call in the Global.asax file.



About the Author

Bipin Joshi

Bipin Joshi is a blogger and writes about apparently unrelated topics - Yoga & technology! A former Software Consultant by profession, Bipin has been programming since 1995 and has been working with the .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. He was a well known technology author, trainer and an active member of Microsoft developer community before he decided to take a backseat from the mainstream IT circle and dedicate himself completely to spiritual path. Having embraced Yoga way of life he now codes for fun and writes on his blogs. He can also be reached there.

Downloads

Comments

  • Regarding MVC Folder structure

    Posted by Kashif on 07/12/2015 06:38am

    Area I am finding difficulties to arrange the area folder for my project This is Job application website and having mainly following type of pages/section 1) - Admin Pages - Only for Admin user(site owners) - so only authenticated(logged in) admin users case see those pages/section example - Post_Jobs_Page, Edit_Job_Page, Change_Admin_Password, Add_News_Events_Page etc. 2) - Job seeker Pages - only for Job seekers - so only authenticated(logged in) Job Seeker users case see those pages/section example - change_Password, Edit_Profile, Applied_Jobs etc 3) - Common Pages - where any job seeker either authenticated(logged in) or without authentication can visit those page Search_Jobs, ContactUs, AboutUs etc So I am not sure how to organize MVC folder structure - how may areas should i add and where to put which files Please help Thanks, Kashif

    Reply
  • layout in area

    Posted by massimo on 05/19/2015 03:45am

    hi, how it's possible to load a layout created in my area ? br max

    Reply
  • Software Developer

    Posted by Saeid on 04/11/2015 03:55pm

    Thanks, Perfect Explanation, It was really helpful.

    Reply
  • ThankYou

    Posted by Gangadhar on 04/24/2013 05:25am

    ThankYou Jeetu Kumar Patra

    Reply
  • Pictures missing

    Posted by Rubem Nascimento da Rocha on 02/28/2013 01:31am

    The article's pictures are missing. I can't view them.

    Reply
  • Awesome

    Posted by N.p Subedi on 02/27/2013 02:07am

    Awesome article. Thank You for posting this.

    Reply
  • Area wise DLL

    Posted by tarak on 02/20/2013 11:23pm

    Hello sir, This article is really a good one. But can you please let me know How can I create AREA specific DLL , so that in future I keep only that DLL and don't disturb other part of the MVC Project. Thanks & Regards, Tarak Bhatt.

    Reply
  • Good Aticle

    Posted by E Jeetu Kumar Patra on 02/13/2013 04:29am

    In case areas we need to another thing for overcoming the conflicts. 1)In main global.asax file and corresponding AreaRegistration.cs file we need to pass value for namespaces parameter in MapRoute method. Ex: In corresponding AreaRegistration.cs context.MapRoute( "default", "AreaName/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional }, new string[] { "AppName.Areas.Jeetu.Controllers" } ); In main MapRoute(in global.asax) routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "MyTime", id = UrlParameter.Optional }, namespaces: new string[] { "AppName.Controllers" } );

    Reply
  • awsome

    Posted by tony on 01/03/2013 02:00pm

    I've been reading many of your blogs, and I can say, that your way of explaining things, organizing paragraph, picture, examples and everything is awsome (your blog : "Creating Custom Action Filters in ASP.NET MVC" is one of the best example). Please keep those blogs comming

    Reply
  • Nice article

    Posted by Juan Vicente on 12/21/2012 08:41am

    Its a really nice and easy demo, only miss show in the page, because in the Code.zip is, the line ControllerBuilder.Current.DefaultNamespaces.Add("AreaDemo.Controllers"); in the method RegisterRoutes of the global.asax for the cases that theres various controllers with same name

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date