How to use Areas in ASP.NET Core MVC

This blog explains how to create Area in ASP.NET Core MVC application, how to use the route for area, configure default area route, link controller action methods from different areas.

ASP.NET Core MVC Area is a feature to divide your large application into a small logical group. Areas help to manage application in a better way to separate each functional aspect into different Areas.

Each Area has its own MVC structure by having subfolders for Models, Views, and Controller. For example, in an organization application, you will have a separate area for Employee, Department, Payroll, Attendance, Expense, etc.

Follow the below steps to create an ASP.NET Core MVC application, create different Areas and use its features.

  1. Create ASP.NET Core MVC application

    Start your Visual Studio and create an MVC application. From Visual Studio Create a new Project template, select ASP.NET Core Web application click Next.
    Enter Project name as AreaDemo, enter a location to be used to store this solution, and click Create.
    In the next window you will see two dropdowns, from the left dropdown select .Net Core, and from the right dropdown select .Net Core 5.0 or more -> Select ASP.NET Core Web App(Model View Controller) and then click Create.

    This creates an ASP.NET Core MVC application with a default file structure having folders for Models, Views, Controllers. To understand the entire file structure and more details about ASP.NET Core MVC application visit - ASP.NET Core MVC5 with .NET 5

  2. Create ASP.NET Core MVC Area

    To add a new Area, Right Click on application name from solution explorer -> Select Add -> Select New Scaffolded Item -> select MVC Area from middle pane of dialog box -> Enter Name of Area -> Click Ok.

    If you already have Areas folder in the application you can just right click on Areas folder -> Add -> Area -> -> You will see a template -> from common -> select MVC Area -> give area name as Employee and click Ok.

    For this tutorial, we are going to create two different areas with the name Department and Employee.

    This creates a Areas folder and subfolder with Department and Employee. The Area has subfolders with name Models, Views and Controllers as shown in below diagram.

    ASP.NET Core MVC Area example

  3. ASP.NET Core MVC Area Route

    The default route is added to the application. To redirect the client to the correct Area you will have to create endpoint routes.

    If you want to set a specific Area route you can use the following route.

    endpoints.MapAreaControllerRoute(
        name: "Department",
        areaName: "Department",
        pattern: "Department/{controller=Sales}/{action=Index}"
    );
            

    The above code will redirect requests to the Sales controller of the Department area. Following URL patterns will be redirected to it.

    • http://domainname.com/department
    • http://domainname.com/department/sales
    • http://domainname.com/department/sales/index

    However in this example Area name was explicitly specified, you can use the following code for generic area name configuration. This code will work for any area which is not configured explicitly.

    endpoints.MapControllerRoute(
        name: "areaRoute",
        pattern: "{area:exists}/{controller}/{action}"
    );
            

    Note that a specific route should be created before the generic route. The following code declares route for Department first, then generic route for Area, and then the default route. This routing configuring multiple custom areas.

    public void Configure(IApplicationBuilder app, 
        IWebHostEnvironment env)
    
        app.UseEndpoints(endpoints =>
        {
    
        endpoints.MapAreaControllerRoute(
            name: "Department",
            areaName: "Department",
            pattern: "Department/{controller=Home}/{action=Index}"
        );
    
        endpoints.MapControllerRoute(
            name: "areaRoute",
            pattern: "{area:exists}/{controller}/{action}"
        );
    
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}"
        );
    
        });
        
    }
    
  4. Create Models

    In this step, we will add models to Department and Employee Area. Right-click on Areas -> Department -> Models folder and add a new class file with the name Location.cs and add the following code to it. This model will be used for the Sales Department location.

    namespace AreaDemo.Areas.Departments.Models
    {
        public class Location
        {
            public int ID { get; set; }
    
            public string Address { get; set; }
    
            public string City { get; set; }
        }
    }
    

    To add Employee model right-click on Areas -> Department -> Models and a new class with file name Employee.cs. A View from Employee area will be using this model to show employees from a specific location of the sales department.

    Add the following code in Employee.cs to define the Employee model

    
    namespace AreaDemo.Areas.Employee.Models
    {
        public class Employee
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string Designation { get; set; }
            public int LocationID { get; set; }
        }
    }
    
    
  5. Areas specific Controller and Action Method

    As Area is meant to partition large Web applications into smaller logical groups. So Department related functionality will be added to Department Area and Employee related functionality will be added to Employee Area.

    You can add multiple controllers, views, and models that are related to the specific features. Here add SalesController that is related to Department Area.

    Add SalesController under Areas -> Department -> Controllers folder. You will have a default MVC Action method with name Index in SalesController.cs file

    Similarly, add a controller under the Areas -> Employee -> Controllers folder with the name EmployeeController.

    Add following code to SalesController. This code creates and bind list of model objects.

    namespace AreaDemo.Areas.Departments.Controllers
    {
        [Area("Department")]
        public class SalesController : Controller
        {
            public IActionResult Index()
            {
                Location[] salesLocation = new Location[] {
                    new Location 
                    { 
                        ID = 1, 
                        Address = "A Road",
                        City = "Pune"                    
                    },
                    new Location
                    {
                        ID = 2,
                        Address = "B Road",
                        City = "London"
                    },
                    new Location
                    {
                        ID = 3,
                        Address = "K Road",
                        City = "New York"
                    },
                };
                return View(salesLocation);
            }
        }
    }
    
    

    In the Employee area add a controller with the name SalesEmployeeController.cs. This controller will have an Action method to display employee lists from a specific locations. This action method will be called from different areas.

    Add following code to SalesEmployeeController.

    
    namespace AreaDemo.Areas.Employee.Controllers
    {
        [Area("Employee")]
        public class SalesEmployeeController : Controller
        {        
    
            [HttpGet]
            
            public IActionResult GetEmployeeListByLocation(int locationID)
            {
               Models.Employee[] employees = new Models.Employee[] {
                    new Models.Employee
                    {
                        ID = 1,
                        Name = "Robert",
                        Designation="Manager",
                        LocationID=1
                    },
                    new Models.Employee
                    {
                        ID = 2,
                        Name = "Steve",
                        Designation="Developer",
                        LocationID=1
                    },
                    new Models.Employee
                    {
                        ID = 3,
                        Name = "Rajan",
                        Designation="CEO",
                        LocationID=2
                    },
                };
    
                Models.Employee[] empList = 
                    employees.Where(item => item.LocationID == locationID).ToArray();
    
                return View(empList);
            }
        }
    }
    
    
  6. Area Specific Views

    In this step, you will add views for Department and Employee Area. Department Area View will display the list of sales locations with the link to see employees that belong to a specific locations.

    Add a view under Areas -> Department -> Views -> Sales folder with name Index.cshtml. Add following HTML code to it.

    
    @model IEnumerable<AreaDemo.Areas.Departments.Models.Location>
    
    @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    @addTagHelper *, AuthoringTagHelpers
    
    @{
        Layout = "~/Views/Shared/_layout.cshtml";
    }
    
    <div class="table-responsive">
    <table class="table table-striped">
    <thead class="thead-dark">
        <tr>
            <th>ID</th>
            <th>Address</th>
            <th>City</th>
            <th>Employee List</th>
        </tr>
    </thead>
    <tbody>
    @foreach (var p in Model)
    {
        <tr>
            <td>@p.ID</td>
            <td>@p.Address</td>
            <td>@p.City</td>
            <td>
            <a asp-area="Employee" 
                asp-controller="SalesEmployee"
                asp-action="GetEmployeeListByLocation"
                asp-route-locationID=@p.ID>
                    View Employee List
            </a>
            </td>
        </tr>
    }
    </tbody>
    </table>
    </div>
    

    if you redirect to http://localhost:<port number>/department/sales. You will see the following output.

    ASP.NET Core MVC Area

    Notice the link "View Employee List" links to the different areas using the asp-area attribute of the anchor tag. The asp-route-locationID passes locationID to Action method of Employee Area.

    To display the Employee List from a specific sales location, add a view under Areas -> Employee -> Views -> SalesEmployee folder. The name of the view should be the same as the action method created in the Employee controller. So name it as GetEmployeeListByLocation.cshtml.

    Add the following HTML code to it.

    @model IEnumerable<AreaDemo.Areas.Employee.Models.Employee>
    @{
        Layout = "~/Views/Shared/_layout.cshtml";
    }
    
    <div class="table-responsive">
    <table class="table table-striped">
    <thead class="thead-dark">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Designation</th>
            <th>LocationID</th>
        </tr>
    </thead>
    <tbody>
    @foreach (var p in Model)
    {
        <tr>
            <td>@p.ID</td>
            <td>@p.Name</td>
            <td>@p.Designation</td>
            <td>@p.LocationID</td>
        </tr>
    }
    </tbody>
    </table>
    </div>
    
    

    Multiple Area file structure will look like this.

    ASP.NET Core MVC Multiple Areas

  7. Call Area specific Action method

    There are multiple ways you can call an action method from a different or same Areas. All of the following ways call an Action method Index from the Home controller of the Admin Area.

    
    <a asp-area="admin" asp-controller="Home" asp-action="index">Go to Admin Area</a>
    
    <a href="@Url.Action("index","home",new {Area="admin"})">Go to Admin Area</a>
    
    <a href="/admin/Home/index">Go to Admin Area</a>
    
    

    You can also redirect to any action method from same or different Area. The following code redirects current action method to Home controller's, index action method, of Admin Area.

    public RedirectToActionResult RedirectToActionResultTest()
    {   
        //Redirects to Index Action Method from Home Controller of Admin Area
    
        return RedirectToAction(actionName: "Index", controllerName: "Home", 
            new { area = "Admin" });
    }
    


Source code on Git hub Source Code on Github

Speak your mind
Please login to post your comment!