Areas and Routing in ASP.NET Core

Areas and Routing in ASP.NET Core

The concept of Routing is very vast and I have covered it in 6 tutorials which are:

So make sure you cover each of these one by one.

Areas in ASP.NET Core 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 folders for Controllers, Model and Views.

Create a new Area called ‘Sales’

To create a new Area in your website, right click on your application name in the solution explorer and select Add ➤ New Folder and name this folder Areas. Create another folder inside this newly created Areas folder and name it as Sales. Now create folders for Controllers, Models & Views inside it. I have illustrated it on the below image:

areas in asp.net core
Built-In Tag Helpers in ASP.NET Core ia a must know topic. They perform common tasks like creating forms, showing validation messages, binding elements with Model, etc.
Creating Route for Areas

You have to add a route to target Areas. For this add the below route inside the Configure() method of Startup.cs class:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "areas",
        pattern: "{area:exists}/{controller=Home}/{action=Index}");
});

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 must 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 new 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 new 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.

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 – https://localhost:58470/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

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>
You can also create Custom Tag Helper in ASP.NET Core so that these tag helpers behave in the manner you want. This way you can create custom HTML Controls in your website.

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.

First create another folder inside the Areas folder and name it as Employee. Now create folders for Controllers, Models & Views inside this newly added folder.

Secondly add a Controller by name Home in the Employee area’s Controllers folder 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 (i.e. ‘Employee’), inside the Index Action of the Home Controller of the Sales Area.

<a asp-action="List" asp-controller="Home" 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

You can target the controllers of the application form the areas by using asp-area="" tag helper.

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 ASP.NET Core . Use it to 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.