Razor Pages in ASP.NET Core

Razor Pages is a page-focused programming model for building web UIs with ASP.NET Core. It provides a simpler, higher-productivity alternative to the MVC pattern for many web applications. Razor Pages makes it easier to build dynamic web UIs.

What are Razor Pages?

A Razor Page is a code file named .cshtml that contains a Razor syntax page. Razor syntax combines HTML, C#, and Razor syntax. A Razor Page is composed of two files:

  • A .cshtml file: Contains HTML markup, Razor syntax, and C# code.
  • A .razor file (optional): Contains the C# code-behind for the Razor Page. This is where you handle logic, data fetching, and event handling.

Key Concepts

Page Models

Each Razor Page typically has an associated "Page Model," which is a class inheriting from PageModel. This class contains properties and methods that are bound to the UI elements in the .cshtml file. It's where you put your page-specific logic.

// Pages/Index.cshtml.cs using Microsoft.AspNetCore.Mvc.RazorPages; public class IndexModel : PageModel { public string Message { get; set; } public void OnGet() { Message = "Welcome to Razor Pages!"; } }

Handler Methods

Razor Pages supports convention-based handler methods for handling HTTP requests. These methods are named OnGet(), OnPost(), OnPut(), etc., corresponding to the HTTP verb. You can also define specific handlers like OnGetUserName(string name).

// Pages/Index.cshtml @page @model IndexModel @{ ViewData["Title"] = "Home page"; }

@Model.Message

// Pages/Index.cshtml.cs (continued) public class IndexModel : PageModel { public string Message { get; set; } public void OnGet() { Message = "Welcome to Razor Pages!"; } public IActionResult OnPost() { Message = "Form submitted!"; return Page(); // Re-render the page } }

Layout Pages

You can use layout pages (_Layout.cshtml) to define a consistent look and feel across your Razor Pages, similar to ASP.NET MVC.

Partial Views

Razor Pages can also render partial views for reusable UI components.

Getting Started

To get started with Razor Pages, create a new ASP.NET Core Web Application project in Visual Studio or using the .NET CLI. Choose the "Web Application" template which uses Razor Pages by default.

Benefits of Razor Pages

  • Simplicity: Easier to learn and use than MVC for many scenarios.
  • Productivity: Faster development for page-focused applications.
  • Organization: Pages and their logic are collocated, improving maintainability.
  • Testability: Page Models are easy to unit test.

Explore the following resources to deepen your understanding: