Razor Pages Guide
Razor Pages is a page-based programming model for building web UI with ASP.NET Core. It provides a clean separation of concerns by combining HTML markup with C# code in the same file, enabling rapid development of dynamic web content.
Introduction to Razor Pages
Razor Pages was introduced in ASP.NET Core 2.0 as a simpler alternative to MVC for building web applications. It's ideal for scenarios where you need a page-focused model, such as:
- Form handling
- CRUD operations for individual resources
- Creating dynamic content sections
Each Razor Page consists of two main parts:
- Razor Page (.cshtml): Contains the HTML markup and Razor syntax for rendering the UI.
- Code-Behind Class (.cshtml.cs): Contains the C# code that handles logic, data binding, and HTTP requests for the page. This class inherits from
PageModel
.
Creating Your First Razor Page
To create a Razor Page, you typically add a new file with a .cshtml
extension to the Pages
folder in your ASP.NET Core project. For example, let's create an Index
page:
@page
@model IndexModel
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core/razor-pages">building Web apps with Razor Pages</a>.</p>
</div>
Alongside the .cshtml
file, you'll have a code-behind file, Index.cshtml.cs
:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace YourApp.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
// This method handles GET requests for the page.
// You can perform initialization logic here.
}
}
}
Page Handlers
Razor Pages use special methods called Page Handlers to handle HTTP requests. These methods are named using a convention: On[HTTP Verb][Optional Parameter Name]
.
OnGet()
: Handles GET requests.OnPost()
: Handles POST requests.OnGet(int id)
: Handles GET requests with an integer parameter.OnPostSave()
: Handles POST requests to a specific action named "Save".
You can have multiple OnPost
methods to handle different form submissions on the same page.
Data Binding
Razor Pages support powerful data binding capabilities, allowing you to easily bind form elements to properties in your PageModel
.
In your .cshtml.cs
file, define properties:
public class ContactModel : PageModel
{
[BindProperty]
public string Name { get; set; }
[BindProperty]
public string Email { get; set; }
public void OnGet() { }
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page(); // Re-render the page with validation errors
}
// Process the submitted Name and Email
return RedirectToPage("/Success");
}
}
In your .cshtml
file, use the asp-for
tag helper for binding:
@page
@model ContactModel
<form method="post">
<div>
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
</div>
<div>
<label asp-for="Email"></label>
<input asp-for="Email" />
<span asp-validation-for="Email"></span>
</div>
<button type="submit">Submit</button>
</form>
Layouts and Partial Views
Like ASP.NET Core MVC, Razor Pages can utilize layouts and partial views to share common UI elements.
- Layouts: Define the overall structure of your application (e.g., header, footer, navigation). The default layout is typically found in
Pages/Shared/_Layout.cshtml
. - Partial Views: Reusable chunks of HTML that can be rendered within other Razor Pages or layouts.
Routing
Razor Pages use a convention-based routing system. By default, pages in the Pages
folder are routed based on their file path relative to the Pages
folder.
Pages/Index.cshtml
maps to the root URL (/
).Pages/About.cshtml
maps to/About
.Pages/Products/Details.cshtml
maps to/Products/Details
.
You can customize routing using the @page
directive's "{route}"
attribute or by configuring routing in Startup.cs
(or Program.cs
in .NET 6+).
Advanced Features
- Tag Helpers: Enhance HTML attributes and elements, enabling server-side logic in your markup.
- Model Validation: Use data annotations to define validation rules for your
PageModel
properties. - Dependency Injection: Inject services into your
PageModel
constructors. - Authorization and Authentication: Integrate ASP.NET Core's security features.
Razor Pages offer a streamlined approach to building modern, interactive web applications with ASP.NET Core, balancing ease of use with powerful features.