ASP.NET Core Razor Pages Application

Exploring ASP.NET Core Razor Pages Application

In this article, I am going to show you how to develop ASP.NET Core Razor Pages Application step-by-step with an example. Razor Pages are Introduced as part of .NET Core 2.0. It is a server-side rendered, page-based model for building web UI with ASP.NET core. Razor pages use Razor syntax.

  1. Server-Side Rendering: Dynamically generates the HTML & CSS on the server side in response to a browser request. The page arrives at the client side which is ready for display. All the logic and the page generation are handled on the server side.
  2. Page-Based Model: Razor pages contain two files which are “.cshtml” and “.cshtml.cs”. The “.cshtml” file contains the UI code and the “.cshtml.cs” file contains the business logic and the page model. All the .NET Core features like dependency injection, middleware, and routing is available in the Razor Pages application.
  3. Razor Syntax: It is a simple programming syntax for embedding server-based code in a web page. Razor syntax combines HTML and C# to define the dynamic rendering logic. We can use C# variables and methods within HTML markup to generate dynamic web content on the server at runtime.
Creating ASP.NET Core Razor Pages Application

Step 1: Launch Visual Studio 2022 and click on “Create a new project” as shown in the below image.

Creating ASP.NET Core Razor Pages Application

Step 2: From the Create a New Project window, select the “ASP.NET Core Web App” project and click on the Next button as shown in the below image.

ASP.NET Core Web App

Step 3: From the Configure your new project window, give a meaningful name to the Project and Solution such as RazorPagesDemo, select the location where you want to create the Project, and then click on the Next button as shown in the below image.

Exploring ASP.NET Core Razor Pages Application

Step 4: From the Additional Information window, select .NET 6.0 (Long-Term Support) as the Framework and leave other options as default. Authentication type: None and “Configure for HTTPS” and do not use top-level statements checkboxes are checked. Click on the Create button as shown in the below image.

.NET 6.0 (Long-Term Support)

Step 5: ASP.NET Core Razor Pages Application is Created.

Once you click on the Create Button the Project is going to be created with the following structure.

ASP.NET Core Razor Pages Application is Created

Let us understand the project structure in detail.

  • wwwroot: It is the project’s web root directory. Like other .NET core projects, wwwroot folder contains all the static files .css, .js, and bootstrap files.
  • Pages: All the Razor pages should be under the Pages folder or within a sub-directory under the Pages folder. As discussed before, each Razor page contains two files. “.cshtml” and “.cshtml.cs”. The “.cshtml” file contains HTML markup with C# code using Razor syntax. The “.cshtml.cs” file has the C# code that handles page events.
  • Shared: Shared folder under the Pages folder contains “_Layout.cshtml”. It is the default layout for the ASP.NET core app. It includes an app header, footer, and navigation.

Exploring ASP.NET Core Razor Pages Application

  • appsettings.json: Contains configuration data (connection string etc.) like other .NET core projects “_ViewImports.cshtml”, and “_ViewStart.cshtml” are helper pages to get started with Razor Pages.
Build and Start the Created Project

Click on the highlighted button to start debugging the project using the Kestrel web server which is enabled by default in ASP.NET core projects.

Build and Start the Created Project

The application will launch and you will get the following welcome page.

Build and Start the Created Project

Sample application to understand how the verb Get() works in razor pages. In this example, we create a new razor page “Get Employee” which displays the First Name of the employee for the given Id.

We create a nav-bar item for the Get Employee page. The Get () verb takes an Id parameter and returns the First Name of the employee. To keep things simple, we are using the in-memory collection as the data source.

Step1: Create a nav-bar item to navigate to the “Employee” Razor Page

Open the _Layout.cshtml file and then add the following code just after the Privacy list item.

<li class="nav-item">
      <a class="nav-link text-dark" asp-area="" asp-page="/Employee">GetEmployee</a>
</li>

Once you add the above code within the _Layout.cshtml file, your code should look as shown below.

Create a nav-bar item to navigate to the “Employee” Razor Page

Step2: Create a Razor Page Employee under the Pages Folder

Right-click on the Pages folder, select Add and then select Razor Page as shown in the below image.

Create a Razor Page “Employee” under the Pages Folder

Then, select the “Razor Page – Empty” item and click on the Add button as shown in the below image.

Razor Page – Empty Item

Next, give the file name as “Employee.cshtml” and click on the Add button as shown in the below image.

ASP.NET Core Razor Pages Application

Once you click on the Add button, it will create Employee.cshtml page within the Pages folder as shown in the below image.

ASP.NET Core Razor Pages Application

Step3: Create an Employees class and add properties

Right-click on your project root directory and then add a new class file with the name Employees.cs and then copy and paste the following code into it.

namespace RazorPagesDemo
{
    public class Employees
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}
Step4: Creating Data Source

For simplicity, we are going to use the in-memory collection as the data source. So, include the builder.Services.AddTransient<List<Employees>>(); as transient for dependency injection in Program.cs file. So, with this line, your Main method of the Program class should look as follows:

namespace RazorPagesDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddRazorPages();

            //Adding Data Source
            builder.Services.AddTransient<List<Employees>>();
            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.MapRazorPages();

            app.Run();
        }
    }
}

Dependencies are injected through the constructor. Create a constructor which takes a parameter “List<Employees>” within the “EmployeeModel” class. Create a property and assign it to it. Create some data for the collection as shown in the below image.

Creating Data Source

Then create a Bindable property called Id which also should support Get within the same EmployeeModel class as shown in the below image.

Creating Data Source

Then update the “Get” verb to include a parameter Id. If the Id is not passed in the URL, set the Id to 1 to avoid the exception. Since we don’t have an employee with Id = 0 as shown in the below image.

Creating Data Source

So, open Employee.cshtml.cs class file which you can find inside the Employee.cshtml which is inside the Pages folder which contains the EmployeeModel class. Then copy and paste the following code into it.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorPagesDemo.Pages
{
    public class EmployeeModel : PageModel
    {
        //Create a variable to hold list of Employees
        public List<Employees> EmployeeList { get; set; }

        //Constructor Taking List<Employees> as a Parameter
        public EmployeeModel(List<Employees> listOfEmployees)
        {
            EmployeeList = listOfEmployees;
            EmployeeList.Add(new Employees() { Id = 1, FirstName = "Akshay", LastName = "Kumar" });
            EmployeeList.Add(new Employees() { Id = 2, FirstName = "Aravind", LastName = "Patil" });
            EmployeeList.Add(new Employees() { Id = 3, FirstName = "Bhanu", LastName = "Prasad" });
        }
        
        [BindProperty(SupportsGet = true)]
        public int Id { get; set; }
        public void OnGet(int Id)
        {
            if (Id == 0)
            {
                this.Id = 1;
            }
        }
    }
}
Step 5: Displaying Employee First Name in Employee.cshtml Razor View

Make changes to Employee.cshtml razor view page to display the employee’s first name. Also, update the title of the page to “Get Employee Page”. Add a table within a div. Display the Name within the first td tag. Here we are using the “@” symbol to write the C# code with the razor view page. “@Model.employeeList.Where(x => x.Id == Model.Id).FirstOrDefault().FirstName”. So, copy and paste the following code into the Employee.cshtml razor view.

@page
@model RazorPagesDemo.Pages.EmployeeModel
@{
    ViewData["Title"] = "Get Employee Page";
} 
<div>
    <table>
        <tr>
            <td>
                <label>Name: @Model.EmployeeList.FirstOrDefault(x => x.Id == Model.Id)?.FirstName</label>
            </td>
        </tr>
    </table>
</div>
Step 6: Save the Changes and Run the Application

After making all these changes, build and start the application. When the application launches. Notice that a new nav-bar item “GetEmployee” is showing up

Save the Changes and Run the Application

Now, Click on the “GetEmployee” nav-bar item

  • Notice that the page title has been changed to “Get Employee Page
  • Notice that we have not passed the Id in the URL
  • We have added a condition in the Get verb to set Id to 1 if it is 0
  • The name “Akshay” displayed corresponds to the employee with Id = 1

ASP.NET Core Razor Pages Application

Now, Pass Id = 2 in the URL using the query string. The name “Aravind” displayed corresponds to the employee with Id = 2 as shown in the below image.

ASP.NET Core Razor Pages Application

In this article, I am just exploring ASP.NET Core Razor Pages Application and in our upcoming articles, we will discuss everything in detail of ASP.NET Core Razor Pages Application. I hope you enjoy this ASP.NET Core Razor Pages Application article.

Leave a Reply

Your email address will not be published. Required fields are marked *