liveBook · Manning

Model directive

As explained in ASP.NET Core in Action, 3e

The @model directive is a Razor directive that declares the PageModel type associated with a Razor Page.

The @model directive declares the PageModel type associated with a Razor Page. Place it after @page, typically on the first lines of the .cshtml file, so ASP.NET Core knows which PageModel to use. section 13.1.3 section 17.2.1

Associate a page with its PageModel

A Privacy.cshtml page can declare @model PrivacyModel. The corresponding PrivacyModel class is conventionally defined in Privacy.cshtml.cs. A ToDoItem page similarly uses @model ToDoItemModel. section 13.1.3 section 17.2.1

The directive determines how Razor Pages process a request:

  • After routing selects a Razor Page, the framework reads @model to choose the associated PageModel. section 17.2.1
  • The selected PageModel supplies strongly typed public properties that the Razor view can use to generate HTML. section 17.5
  • The framework can bind [BindProperty] properties and execute a page handler appropriate to the request’s HTTP verb. section 17.2.1
  • A PageModel and @model directive are optional; without them, the framework can execute an implicit handler and render the view directly. section 17.2.1
Listing 13.3 The Privacy.cshtml Razor Page
@page                                                         #1
@model PrivacyModel                                           #2
@{
    ViewData["Title"] = "Privacy Policy";                     #3
}
<h1>@ViewData["Title"]</h1>                                   #4
 
<p>Use this page to detail your site's privacy policy.</p>    #5

Inspect the complete Privacy.cshtml example, including @page, @model PrivacyModel, ViewData, and rendered markup. section 13.1.3

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains placement, type association, request processing, binding, and handler execution, while deferring PageModel details.
Examples
Uses PrivacyModel and ToDoItemModel declarations, including the conventional .cshtml.cs code-behind pairing.
What it assumes
Assumes familiarity with Razor Pages and @page, while showing the PageModel association from the basic page structure.
What you can do after
Apply the directive to associate a Razor Page with a PageModel and access its typed properties during HTML generation.
How it connects
Connects Razor Pages with PageModel, Razor views, page handlers, model binding, HTTP verbs, and strongly typed data.

Also explained in

Compare how 2 books explain model directive →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.