Areas and Routing in ASP.NET Core

Areas and Routing in ASP.NET Core

Areas in ASP.NET Core MVC represent a functional segment of the application. It can be administration, billing, sales, etc. If your application becomes very large then it will have many controllers, Models & Views.

Here you can create Areas to distribute the application files into them. This will help you manage your application in a better way as it becomes obvious which files are related to which functional aspect of the application.

Areas have their own MVC folder structure i.e. they have their own Controllers folder, Model folder and Views folder.

To create a new Area in your website, right click on your application name in the solution explorer and select Add ➤ Area. When asked for its name give it ‘Sales’.

All Areas are created inside the Areas folder in the root. Open the Areas folder to see the Sales folder is created and it contains the folders for Controller, Model & View, as shown in the below image:

areas in asp.net core

Creating Route for Areas

You have to add a route to target Areas. For this add the below route inside the Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseDeveloperExceptionPage();
    app.UseStatusCodePages();
    app.UseStaticFiles();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "areas",
            template: "{area:exists}/{controller=Home}/{action=Index}");

        //Default Route
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

The area segment matches URLs that target controllers in specific areas.

The exists constraint is used to match request to areas that are created.

You add the areas routes before less specific routes.

Creating Model, View and Controller for the Sales Area

To show how the Sales Area will work, create a Model class inside the Models folder of the Sales Area. Name this class as Product.cs with the code shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace URLRouting.Areas.Sales.Models
{
    public class Product
    {
        public string Name { get; set; }
        public int Quantity { get; set; }
        public int Price { get; set; }
    }
}

Now create a Controller inside the Controllers folder of the Sales Area. Name the Controller as ‘HomeController’. Add the below code to it:

using Microsoft.AspNetCore.Mvc;
using URLRouting.Areas.Sales.Models;

namespace URLRouting.Areas.Sales.Controllers
{
    [Area("Sales")]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            Product[] productArray = new Product[] {
                new Product { Name = "Pants", Quantity = 5, Price=100 },
                new Product { Name = "Shirts", Quantity = 10, Price=80 },
                new Product { Name = "Shoes", Quantity = 15, Price=50 }
            };
            return View(productArray);
        }
    }
}

Notice the [Area(“Sales”)] attribute applied to the Controller. It is used to associate a Controller with the Sales area. It is a requirement and don’t forget to add it.

To include namespaces and take advantage of tag helpers create View Imports (_ViewImports.cshtml) file in the ‘Areas/Admin/Views’ Folder and add the following code to it:

@using URLRouting.Areas.Sales.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

The final part is adding an Index View which you add inside the ‘Areas/Admin/Views/Home’ folder having the contents as shown below:

@model Product[]
@{ Layout = null; }

<!DOCTYPE html>
<html>
<head>
    <title>Routing</title>
</head>
<body>
    <table>
        <tr><th>Name</th><th>Quantity</th><th>Price</th></tr>
        @foreach (URLRouting.Areas.Sales.Models.Product p in Model)
        {
            <tr><td>@p.Name</td><td>@p.Quantity</td><td>@p.Price</td></tr>
        }
    </table>
</body>
</html>

Run your application and go to the URL – ‘/Sales’. You will see the Index Action of the Home Controller of the Sales Area getting displayed as shown by the image below:

working of areas

Creating Links in Areas

If use the asp-action=”action_name” tag helper then it will create the link to an action method of the same area.

Example: Create a link by adding the below code to the Index Action of the Home Controller of the Sales Area.

<a asp-action="List">Link1</a>

The link formed will be:

<a href="/Sales/Home/List/">Link1</a>

To target another Controller’s action method of the same Area, you can use the asp-controller=”controller_name” tag helper as shown below:

<a asp-action="List" asp-controller="Report">Link</a>

The link formed in this case is:

<a href="/Sales/Report/List/">Link</a>

The ‘asp-route-area’ Tag Helper

The asp-route-area attribute targets the area segment variable. To test it create a new area in your application and name it ‘Employee’. Add a Controller by name ‘Home’ in that area with the codes shown below:

using Microsoft.AspNetCore.Mvc;

namespace URLRouting.Areas.Employee.Controllers
{
    [Area("Employee")]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

Now add the below code to target this area (Employee) inside the Index Action of the Home Controller of the Sales Area.

<a asp-action="List" asp-controller="Report" asp-area="Employee">Link3</a>

You will find the link formed in this case is:

<a href="/Employee/Home/List">Link3</a>

Targeting main part of the application from the Area

Form the area you can target the controllers that are on the main part application of the application by providing asp-area=””.

To test it add the below code in the Index Action of the Home Controller of the Sales area:

<a asp-route-area="" asp-action="List" asp-controller="Home">Link4</a>

The link formed in this case will be:

<a href="/Home/List/">Link4</a>

You can download the full codes of this tutorial from the below link:

Download

Conclusion

I explained all about Areas and Routing feature of Core 2.0. You can now create URLs in the way you want. I hope you will find it very helpful.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.