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.
Razor Pages is a great choice for building web apps due to its:
Here’s a simple example of setting up and using Razor Pages:
// 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.
// 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.
// 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.
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.