Understand when and why to use Razor Pages

Completed

In this unit, you'll learn when and why to use Razor Pages for your ASP.NET Core app.

The benefits of Razor Pages

Razor Pages is a server-side, page-centric programming model for building web UIs with ASP.NET Core. Benefits include:

  • Easy setup for dynamic web apps using HTML, CSS, and C#.
  • Organized files by feature for easier maintenance.
  • Combines markup with server-side C# code using Razor syntax.

Razor Pages utilize Razor for embedding server-based code into webpages. Razor syntax combines HTML and C# to define the dynamic rendering logic. This means you can use C# variables and methods within your HTML markup to generate dynamic web content on the server at runtime. It's important to understand that Razor Pages are not a replacement for HTML, CSS, or JavaScript, but rather combines these technologies to create dynamic web content.

Separation of concerns

Razor Pages enforces separation of concerns with a C# PageModel class, encapsulating data properties and logic operations scoped to its Razor page, and defining page handlers for HTTP requests. The PageModel class is a partial class that is automatically generated by the ASP.NET Core project template. The PageModel class is located in the Pages folder and is named after the Razor page. For example, the PageModel class for the Index.cshtml Razor page is named IndexModel.cs.

When to use Razor Pages

Use Razor Pages in your ASP.NET Core app when you:

  • Want to generate dynamic web UI.
  • Prefer a page-focused approach.
  • Want to reduce duplication with partial views.

Razor Pages simplifies ASP.NET Core page organization by keeping related pages and their logic together in their own namespace and directory.

Note

ASP.NET Core also supports the Model-View-Controller (MVC) pattern for building web apps. Use MVC when you prefer a clear separation between Model, View, and Controller. Both Razor Pages and MVC can coexist within the same app. MVC is outside the scope of this module.

In the next unit, you'll take a tour of a Razor Pages app.

Check your knowledge

1.

Which one of the following statements is true for Razor Pages?