Introduction to ASP.NET Core Razor Pages

Learn the fundamentals of Razor Pages, a page-centric programming model for building dynamic, data-driven, web UI with ASP.NET Core.

What are Razor Pages?

Razor Pages is a page-centric programming model in ASP.NET Core for building web UI. It's a simpler alternative to Model-View-Controller (MVC) for applications where the primary concern is page-based scenarios, like forms and dynamic content rendering.

Each Razor Page is represented by a Razor file (.cshtml) containing HTML, CSS, and server-side code expressed in Razor syntax. This code-behind model simplifies organizing page-specific logic and UI.

Key Concepts

  • Page Model (.cshtml.cs): A C# class that handles page logic, data handling, and request processing. It inherits from PageModel.
  • Razor View (.cshtml): An HTML file that renders the UI. It can directly reference properties and methods from its associated Page Model.
  • Razor Syntax: A hybrid markup syntax that combines HTML with C# code, allowing for dynamic content generation.

Why Use Razor Pages?

Razor Pages offer several advantages:

  • Simplicity: Ideal for developers familiar with ASP.NET Web Forms or other page-centric models, as it reduces the complexity compared to full MVC for many scenarios.
  • Organization: Co-locates UI and page-specific logic, making it easier to manage related files.
  • Productivity: Faster development for forms and data-driven pages.
  • Unified Model: Provides a consistent way to handle page rendering and request processing.

A Simple Example

Consider a simple page to display a greeting. It would typically involve two files:

Pages/Greeting.cshtml.cs

using Microsoft.AspNetCore.Mvc.RazorPages; public class GreetingModel : PageModel { public string Message { get; private set; } = "Hello!"; public void OnGet() { Message = "Welcome to Razor Pages!"; } }

Pages/Greeting.cshtml

@page @model GreetingModel @{ ViewData["Title"] = "Greeting Page"; }

@Model.Message

When a user navigates to /Greeting, the OnGet method in GreetingModel is executed, setting the Message property. The Greeting.cshtml file then renders this message.

Page Directives

The @page directive at the top of a .cshtml file signifies that it's a Razor Page. The @model directive specifies the Page Model class associated with the view.

Scenarios Where Razor Pages Shine

  • Building forms and processing form submissions.
  • Displaying dynamic data.
  • Creating simple, content-focused websites.
  • Refactoring existing ASP.NET applications to a more modern framework.

Tip: While Razor Pages simplifies many common web development tasks, ASP.NET Core MVC is still a powerful and flexible option for complex applications with intricate separation of concerns.

Next Steps

Now that you have a basic understanding of Razor Pages, you can explore: