Wednesday, July 26, 2023

ASP.NET Core Razor Pages with all about Areas and navigation to their pages

Objectives

  • What is Areas in ASP.NET Core
  • What are benefits of creating Areas
  • How to create Areas in ASP.NET Core project
    • In MVC
    • In Razor Page
  • How to navigate pages in and between different areas

Areas

Areas are used to split a big ASP.NET Core project into manageable parts. Each area refers to almost independent entity in the application. Each area has its own Model, Views, Data and Controllers. For example, in a School project, Student, Teacher and Management are separate areas and they can be independently developed. Area can be used in MVC and Web API. Creating areas in project facilitates the division of development works among the developers and their testing etc.

Benefits of Areas

  • Modularity of the application
  • Division of tasks among developers
  • Efficiency gain in development speed

How to Create Areas

In the root of the application, folder named as Areas is created and different areas are created as subfolders inside the Areas folder. Let's see this by creating a project.
  1. Create web project using ASP.NET Core Web App (Model-View-Controller) template. 
  2. Create a new folder in solution explorer and rename it as Areas. Note that it should be named Areas not Area. 
  3. Right click Areas folder (Add > Area...) to add a new Area in it. Use scaffolding to create subfolders in an area automatically. You can create them manually also.

Create subfolders such as Admin, User, Teacher, Student, Management etc. inside inside Areas folder using scaffolding. Each area will have its own data, controllers, views and models folders created automatically, if you use scaffolding. You can do it manually as well.


Routing in case of Areas in MVC

The routing engine will look at the template to select an action from an area. In Startup class, we map a new route with following parameters as given below.
app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

Navigation In and Between Areas

To navigate inside an area, we follow the old technique as used without Areas. We use anchor tag with asp-page and asp-page-handler attributes if you are using Tag helpers. In case of navigation from one area to another, we must also include as-area attribute in the anchor tag.

Exception in case of Areas

In case of areas, each area has a HomeController and Index action. The application throws exception that it is not able to choose the default Index view. Resolve this issue.

Solution
Use [Area("Admin")] attribute before HomeController in Admin area and [Area("User")] attribute before HomeController in User area. Look at the following code.

[Area("Admin")]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
NOTE: Now the following URLs will work properly.
  • https://localhost:44337/user/home/
  • https://localhost:44337/user/home/Index
  • https://localhost:44337/admin/home/
  • https://localhost:44337/admin/home/Index
In view, we use asp-area attribute in the form control.

Exercise of Areas in Razor Pages. 

Create a login page with two anchor links in an ASP.NET Core Razor page project. In the root Index page,  add two anchor links. One anchor link navigates the user to Teacher area and another one to Student area.

Solution.

Important. Each area MUST have Pages folder and then any Razor Page in it. Otherwise area will not work in Razor pages. Create Pages folder manually in each area of the Razor page app. At the same time, remember that we can use configuration to change the root folder for Razor pages.
The following example changes the root folder from the default Pages to Content by using AddRazorPagesOptions:

builder.Services.AddRazorPages()
    .AddRazorPagesOptions(options => {
        options.RootDirectory = "/Content";
    });
Or we can use the WithRazorPagesRoot extension method:

builder.Services.AddRazorPages().WithRazorPagesRoot("/Content");

We have added the Index files in Teacher and Student areas including the root of application.

Index.cshtml in Teacher

  
@page
@model RPWebApp.Areas.Teacher.Pages.IndexModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<h1>Inside Teacher/Pages/Index</h1>
<h5>Each Area MUST have Pages folder and then any Razor Page in it.</h5>

<a asp-page="Teacher">Go to Teacher of  Teacher arae</a>
<br/>
<a asp-page="Index">Go to Index of Teacher area</a>
<br/>
<a asp-area="" asp-page="Index">Go to App Root Index</a>

Index.cshtml in Student

@page
@model RPWebApp.Areas.Student.Pages.IndexModel
@{
}
<h1>Student/Pages/Index</h1>
<h5>Each Area MUST have Pages folder and then any Razor Page in it.</h5>
On clicking the links given in the root Index page we navigate to the desired page.

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h5> Root Index Page.</h5>
</div>

<div>
    <h5>Each Area MUST have Pages folder and then any Razor Page in it.</h5>
    <a asp-area="Teacher" asp-page="/Index">Teacher Area</a>
    <br />
    <a asp-area="Student" asp-page="/Index">Student Area</a>
</div>


In the next part we will see how Authorization can be applied in Areas so that based on the roles of the users, access can be granted or denied for an area.

No comments:

Post a Comment

Hot Topics