ASP.NET Razor Page Component Model Overview

This blog post describes my oversimplified understanding of the ASP.NET Core razor page component model.

Razor is a syntax for embedding HTML and C# in .cshtml files that run on the server to generate HTML. Significant C# belongs in other files, but is used in views for data retrieval, looping, and otherwise.

The application determines a model class to pass to each razor component (page view, page view, partial view, or view component).

A razor page consists of a PageModel and a Razor Page Template.

  • Razor PageModel: The PageModel class or a derivative services the request, generally by implementing the OnGet() method to construct a model to pass to the razor page template.
  • Razor Page Template: The razor page template uses razor syntax in a .cshtml file to render data from the PageModel. The .cshtml file contains a @page directive that controls which routes (URL patterns) activate the razor page. By default, this directive requires a separate razor page template for each page serviced by the ASP.NET Core razor pages infrastructure.
  • Layout: While processing seems to start with the page view, if that view specifies a layout, then rendering seems to start with the layout, which is another razor page template. Layouts are reusable superstructures for pages, which means that their models represent data that can apply to any page. Layouts generally contain the <html>, <head>, and <body> elements. The layout calls @RenderBody() to render the razor page template. Towards the end, the layout can render a section to contain JavaScript that may be bundled and minified using ASP.NET Core techniques.
  • Razor Partial View: Partial views are razor templates that retrieve data from and call methods of the model passed to the partial view to generate a section of the page. Partial views are appropriate for rendering when all data and logic is available in the model.
  • Razor View Components: View components are like partial views with an additional class that typically assembles the model for the view template to generate a section of the page. View components are appropriate for constructing more complex models for views.
  • Sections: Another feature of ASP.NET Core razor pages that I will not describe here because I prefer alternatives.

Confusingly, there is also something called a razor component, but these seem to be specific to Blazor apps, which compile C# to WebAssembly that runs like JavaScript.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: