Getting Started with .NET Razor Pages

What are Razor Pages?

Razor Pages is a page-based programming model in ASP.NET Core. It simplifies the process of building web applications by combining the UI and server-side logic into a single page model.

  • Lightweight: Ideal for simple or small-scale applications.
  • Page-Centric: Each Razor Page is tied to a specific route, making it straightforward to handle requests and responses.
  • Easy to Learn: Razor Pages are beginner-friendly, reducing the complexity of MVC by avoiding the separation into Models, Views, and Controllers.

Razor Pages Design Pattern

Why Use Razor Pages?

Razor Pages is a great choice for building web apps due to its:

  • Built-In Razor Syntax: Simplifies writing dynamic HTML using C# code.
  • Improved Maintainability: Keeps logic and UI close together.
  • Integration with ASP.NET Core: Supports dependency injection, middleware, and routing.

How to Use Razor Pages in .NET

Here’s a simple example of setting up and using Razor Pages:

1. Create a Razor Page


// Pages/Index.cshtml
@page
@model IndexModel

Welcome to Razor Pages

Today's date is: @Model.CurrentDate

This is the Razor markup file for your page. The @page directive specifies that it is a Razor Page.

2. Define the Page Model


// Pages/Index.cshtml.cs
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;

public class IndexModel : PageModel
{
    public string CurrentDate { get; private set; }

    public void OnGet()
    {
        CurrentDate = DateTime.Now.ToString("MMMM dd, yyyy");
    }
}

                

The IndexModel class is the page model that contains the logic for the Razor Page. The OnGet method runs when the page is accessed via a GET request.

3. Configure Routing in Startup


// Program.cs
var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();
app.MapRazorPages();
app.Run();

                

Razor Pages are automatically routed when you call app.MapRazorPages() in your program configuration.


Run Your Razor Pages Application

Start the application using the following command:

                    dotnet run
                

Navigate to http://localhost:5000 in your browser, and you’ll see the "Welcome to Razor Pages" message along with the current date.