ASP.NET Core Razor Pages
Razor Pages is a page-centric way to build Razor-based web UI with ASP.NET Core. It offers a simpler, more organized approach to building individual pages compared to traditional MVC.
Note: Razor Pages is the recommended approach for new, page-focused web applications in ASP.NET Core.
What are Razor Pages?
A Razor Page is a set of files that includes:
- A Razor file (
.cshtml
): Contains the HTML markup and Razor syntax. - A PageModel class (
.cshtml.cs
): Contains the code-behind logic, including handlers for HTTP requests and properties for the page.
The PageModel class inherits from PageModel
, providing built-in functionality for request handling, model binding, and dependency injection.
Key Concepts
PageHandler Methods
Razor Pages uses a convention-based approach for handling HTTP requests. Methods named OnGet
, OnPost
, OnPut
, etc., are automatically invoked based on the HTTP verb. You can also define specific handlers for different scenarios.
// Pages/Index.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
public class IndexModel : PageModel
{
public string Message { get; set; }
public void OnGet()
{
Message = "Welcome to Razor Pages!";
}
public IActionResult OnPostSubmit(string name)
{
Message = $"Hello, {name}!";
return Page();
}
}
// Pages/Index.cshtml
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
@Model.Message
Model Binding
Razor Pages automatically binds data from incoming HTTP requests (form values, query strings, route data) to properties on your PageModel.
Dependency Injection
You can inject services into your PageModel class using standard ASP.NET Core dependency injection.
public class MyPageModel : PageModel
{
private readonly IMyService _myService;
public MyPageModel(IMyService myService)
{
_myService = myService;
}
public void OnGet()
{
ViewData["Data"] = _myService.GetData();
}
}
Benefits of Razor Pages
- Simplicity: Easier to understand and develop for than traditional MVC for many scenarios.
- Organization: Keeps UI and logic for a specific page together.
- Code Sharing: Leverage existing Razor and ASP.NET Core features.
- Testability: PageModels are easily testable.
Tip: For complex applications with shared layouts, reusable components, or distinct separation of concerns, consider ASP.NET Core MVC or Blazor.
Getting Started
To create a new Razor Pages project:
- Use the ASP.NET Core Web App template in Visual Studio or via the .NET CLI:
dotnet new webapp -o MyRazorApp
- Organize your pages within the
Pages
folder of your project.
Further Reading
Explore these related topics:
Resource | Description |
---|---|
API Reference | Detailed API documentation for Razor Pages. |
Code Samples | Example implementations and use cases. |
Community Forums | Ask questions and get help from the community. |