Razor Pages
Razor Pages is a page-focused programming model in ASP.NET Core for building dynamic, data-driven HTML-user interfaces with the server.
Overview
Razor Pages provides a simpler, higher-productive alternative to the Model-View-Controller (MVC) pattern for building web UIs. It focuses on pages rather than controllers, making it easier to manage and organize page-specific logic.
Key Concepts
- Page Model: A C# class that inherits from
PageModel
. It contains the logic and data for a specific page. - Razor View: An HTML file with embedded Razor syntax (
.cshtml
). It defines the UI for a page and binds to properties of the Page Model. - Routing: Razor Pages uses a file-based routing convention. The URL path corresponds to the location of the Razor file within the
Pages
folder. - Request Handling: The Page Model can handle HTTP requests (GET, POST, etc.) using methods like
OnGet()
andOnPost()
.
Getting Started
To create a Razor Page:
- In your ASP.NET Core project, create a folder named
Pages
in the project root. - Inside the
Pages
folder, create a new Razor Page. For example, create a file namedIndex.cshtml
. - Optionally, create a corresponding Page Model file named
Index.cshtml.cs
.
Example: A Simple Razor Page
Pages/HelloWorld.cshtml:
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>@Model.Message</h1>
</body>
</html>
Pages/HelloWorld.cshtml.cs:
using Microsoft.AspNetCore.Mvc.RazorPages;
public class HelloWorldModel : PageModel
{
public string Message { get; set; }
public void OnGet()
{
Message = "Hello, Razor Pages!";
}
}
When you navigate to /HelloWorld
, the OnGet()
method will execute, setting the Message
property, and the view will render "Hello, Razor Pages!".
Data Binding
Razor Pages supports robust data binding. You can bind form elements to properties in your Page Model.
Example: Form Submission
Pages/Contact.cshtml:
<h1>Contact Us</h1>
<form method="post">
<div>
<label asp-for="Name"></label>
<input asp-for="Name" />
</div>
<div>
<label asp-for="Email"></label>
<input asp-for="Email" />
</div>
<button type="submit">Send</button>
</form>
Pages/Contact.cshtml.cs:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
public class ContactModel : PageModel
{
[BindProperty]
public string Name { get; set; }
[BindProperty]
public string Email { get; set; }
public void OnGet()
{
// Initialize form fields if needed
}
public IActionResult OnPost()
{
// Process the submitted Name and Email
if (!ModelState.IsValid)
{
return Page(); // Re-render the page with validation errors
}
// Save data, send email, etc.
return RedirectToPage("./ThankYou"); // Redirect to a success page
}
}
Layouts and Partial Views
Razor Pages seamlessly integrates with layout pages (_Layout.cshtml
) and partial views (_Partial.cshtml
) for reusable UI components and consistent page structure.