What is Area and how we create it in MVC?

Posted by  Joseph Rossignol
 508  View(s)
Ratings:
Rate this:

Please describes to me what is Area and how we create an Area in Asp.Net MVC using an example.

  1. Re: What is Area and how we create it in MVC?

    The ASP.NET MVC framework includes separate folders for Model, View, and Controller, however, the large application can include a large number of controller, views and model classes, and so to maintain a large number of views, models, and controllers with the default the ASP.NET MVC project structure which can become unmanageable.

    The ASP.NET MVC 2 introduced Area and this area allows us to partition large application into smaller units where each unit contains separate MVC folder structure, same as default MVC folder structure, for example, large enterprise application contains different modules like admin, finance, HR, marketing, etc. so an Area can contain separate MVC folder structure for all these modules as shown given below:-

    Creating an Area

    • We can create an Area using ASP.NET MVC 5 and Visual Studio 2013 for the web by right-clicking on the project in the solution explorer -> Add -> Area.

    What is Area and how we create it in MVC?

    • Now enter Area name in Add Area dialogue box and then click on Add.

    What is Area and how we create it in MVC?

    • And this will add the 'admin' folder under Area folder as shown given below.

    What is Area and how we create it in MVC?

    • We can see, each area includes AreaRegistration class in AreaRegistration.cs file.

    This following is the adminAreaRegistration class created with the admin area.

    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 }
            );
        }
    }

    Here, the AreaRegistration class overrides RegisterArea method to map the routes for the area and in the above-given example, so any URL that starts with admin will be handled by the controllers which are included in the admin folder structure under Area folder, for example, http://localhost/admin/profile will be handled by the profile controller included in Areas/admin/controller/ProfileController folder.

    At the end all the area must be registered in Application_Start event in Global.asax.cs as AreaRegistration.RegisterAllAreas();

    In this way, we can create and maintain multiple areas for a large application.

Answer