ASP.NET Core Razor Pages API Reference
This document provides a comprehensive API reference for ASP.NET Core Razor Pages, detailing the core classes, interfaces, and attributes that enable you to build dynamic web interfaces with a page-centric model.
Core Concepts
Razor Pages offers a simplified, page-centric approach to building web UIs in ASP.NET Core. It's built on top of ASP.NET Core MVC, providing a lighter-weight alternative for many scenarios.
PageModel Class
The PageModel class is the foundation for your Razor Pages. It represents a single page in your application and contains the logic and data associated with that page.
Key properties and methods include:
Page(): Returns an HTTP 200 OK response.RedirectToPage(string pageName, object routeValues): Redirects to another Razor Page.NotFound(): Returns an HTTP 404 Not Found response.BadRequest(): Returns an HTTP 400 Bad Request response.ModelState: Provides access to the current model state for validation.OnGet(): The handler method executed when the page is requested via an HTTP GET request.OnPost(): The handler method executed when the page is submitted via an HTTP POST request.OnPut(),OnDelete(),OnPatch(): Handlers for other HTTP verbs.
public class MyPageModel : PageModel
{
public string Message { get; set; }
public void OnGet()
{
Message = "Welcome to the Razor Page!";
}
public IActionResult OnPostSubmit(string inputData)
{
if (string.IsNullOrEmpty(inputData))
{
ModelState.AddModelError("inputData", "Input data cannot be empty.");
return Page(); // Return to the same page with errors
}
// Process inputData
return RedirectToPage("./Success");
}
}
Page Directive
The @page directive is essential and must be the first directive in a Razor Page (`.cshtml`) file. It signals to the Razor engine that this file is a Razor Page.
@page
@model MyProject.Pages.MyPageModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@Model.Message
.cshtml vs. .cshtml.cs
Razor Pages follow a convention where the Razor view (`.cshtml`) is paired with a code-behind file (`.cshtml.cs`). The `.cshtml` file contains the HTML markup and Razor syntax, while the `.cshtml.cs` file contains the PageModel class logic.
Common Attributes and Helpers
[BindProperty]: Used on properties in aPageModelto automatically bind form data to the property.[HttpGet],[HttpPost], etc.: Attributes to specify which HTTP methods a handler method responds to.asp-page: Tag helper attribute to generate URLs for Razor Pages.asp-for: Tag helper attribute to bind an HTML element to a model property, including validation.asp-validation-for: Tag helper attribute to display validation messages for a model property.
[BindProperty] Example
// MyPageModel.cshtml.cs
public class InputFormPageModel : PageModel
{
[BindProperty]
public string UserInput { get; set; }
public IActionResult OnPost()
{
// UserInput is automatically populated from the form
if (string.IsNullOrWhiteSpace(UserInput))
{
ModelState.AddModelError("UserInput", "Please enter some text.");
return Page();
}
return RedirectToPage("./Result", new { data = UserInput });
}
}
// MyPageModel.cshtml
@page
@model InputFormPageModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<form method="post">
<label asp-for="UserInput"></label>
<input asp-for="UserInput" />
<span asp-validation-for="UserInput"></span>
<button type="submit">Process</button>
</form>
Common Scenarios
Displaying Data
Use OnGet() to fetch data and assign it to properties on your PageModel. These properties can then be displayed in your Razor view using Razor syntax (@Model.PropertyName).
Handling Form Submissions
Use OnPost() (or other verb-specific handlers) to process data submitted from an HTML form. Use [BindProperty] to simplify data binding.
Validation
ASP.NET Core provides built-in validation support. Decorate your model properties with data annotation attributes (e.g., [Required], [StringLength]) and use asp-validation-for in your view to display error messages.
Routing
Razor Pages have a convention-based routing system. By default, a page located at Pages/MyFolder/MyPage.cshtml will be accessible at the URL /MyFolder/MyPage. You can customize this using the [Route] attribute or by modifying Startup.cs.