Razor Pages in ASP.NET Core

Introduction

Razor Pages is a page-focused programming model for building web UI with ASP.NET Core. It provides a simpler, more direct way to build per-page code-behind logic for your Razor markup. Razor Pages is ideal for scenarios where you need to assemble HTML output using server-side code, without the overhead of traditional MVC patterns for every single feature.

It offers a streamlined approach for developers who prefer a more minimalist and direct way to create web pages compared to the full MVC framework. Each Razor Page consists of two files:

Creating a Razor Page

To create a Razor Page, add a .cshtml file to your project, typically within a Pages folder. For example, Pages/Index.cshtml. You can also associate a C# class with it (the Page Model) by creating a .cshtml.cs file with the same name in the same directory, like Pages/Index.cshtml.cs.

Here's a basic example:

.NET Core ```csharp // Pages/HelloWorld.cshtml.cs using Microsoft.AspNetCore.Mvc.RazorPages; public class HelloWorldModel : PageModel { public string Message { get; private set; } public void OnGet() { Message = "Hello from Razor Pages!"; } } ```
Razor ```html @page @model HelloWorldModel @{ ViewData["Title"] = "Hello World"; }

@Model.Message

This is a simple Razor Page.

```

Page Model

The Page Model is a C# class that inherits from RazorPage or PageModel. It contains the server-side logic for the Razor Page, including properties to bind data and handler methods to respond to requests.

Handler Methods

Razor Pages uses naming conventions for handler methods. Common handlers include:

Tip: You can also use generic handlers like OnGetAsync() and OnPostAsync() for asynchronous operations.

Razor Syntax

Razor syntax allows you to embed C# code within HTML. Key elements include:

Routing

Razor Pages routing is convention-based. The URL path for a Razor Page is determined by its file path within the Pages folder. For example:

You can customize routing using route templates in the @page directive or by decorating handler methods with [Route("...") ] attributes.

Data Binding

Razor Pages supports two-way data binding for form elements. You can bind form inputs to properties on your Page Model.

Razor ```html @page @model ContactModel @{ ViewData["Title"] = "Contact Us"; }

Contact Us

```
.NET Core ```csharp // Pages/Contact.cshtml.cs using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.ComponentModel.DataAnnotations; public class ContactModel : PageModel { [BindProperty] [Required] [Display(Name = "Your Name")] public string Name { get; set; } [BindProperty] [Required] [EmailAddress] public string Email { get; set; } public IActionResult OnPost() { if (!ModelState.IsValid) { return Page(); // Re-render the page with validation errors } // Process the form data (e.g., send an email) return RedirectToPage("./Success"); } } ```

Validation

Use data annotations in your Page Model properties to define validation rules. The <input asp-for="..." /> and <span asp-validation-for="..." /> helpers will automatically render the necessary HTML and display validation messages.

Layout

You can share common UI elements like headers, footers, and navigation using layout files. By default, Razor Pages use Pages/_Layout.cshtml. The RenderBody() method in the layout file renders the content of the current page.

Partial Views

For reusable UI components, you can use partial views. These are Razor files that render a portion of a page.

Razor ```html @await Html.PartialAsync("_MyPartialView", Model.SomeData) ```

Authentication & Authorization

Razor Pages integrates seamlessly with ASP.NET Core's authentication and authorization system. You can apply [Authorize] attributes to Page Models or specific handler methods to restrict access.

Advanced Features

Razor Pages supports various advanced features, including:

Explore the official ASP.NET Core documentation for in-depth details on these topics.