liveBook · Manning

RazorPage<T>

As explained in Pro ASP.NET Core 7, Tenth Edition

RazorPage<T> is the generic base class generated for a Razor view, with T specifying the view model type.

RazorPage<T> is the generic base class generated for a Razor view. The type argument identifies the view model available through the uppercase Model expression. section 21.3.1

Specifying the model type changes how the view is developed and compiled:

  • Without an @model declaration, the generated page uses dynamic, so member names are evaluated at runtime. section 21.3.1
  • With @model WebApp.Models.Product, the generated class derives from RazorPage<WebApp.Models.Product>. section 21.3.1
  • The explicit type enables editor completion and causes invalid members to produce editor, compiler, or browser errors. section 21.3.1
Listing 21.15 Declaring the type in the Watersports.cshtml file in the Views/Home folder
@model WebApp.Models.Product
<!DOCTYPE html>
<html>
<head>
    <link href="/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <h6 class="bg-secondary text-white text-center m-2 p-2">
        Watersports
    </h6>
    <div class="m-2">
        <table class="table table-sm table-striped table-bordered">
            <tbody>
                <tr><th>Name</th><td>@Model.Name</td></tr>
                <tr>
                    <th>Price</th>
                    <td>@Model.Price.ToString("c")</td>
                </tr>
                <tr><th>Category ID</th><td>@Model.CategoryId</td></tr>
                <tr><th>Tax Rate</th><td>@Model.TaxRate</td></tr>
            </tbody>
        </table>
    </div>
</body>
</html>

Declare the Product model at the top of Watersports.cshtml, then access its properties through Model. section 21.3.1

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains generated inheritance, dynamic fallback, typed member access, and resulting editor and build diagnostics.
Examples
Demonstrates a typed Watersports.cshtml view rendering Product properties and correcting an invalid member.
What it assumes
Assumes action methods and view models, while clarifying the distinction between Model expressions and the model directive.
What you can do after
Build typed Razor views with editor completion and compile-time feedback for invalid model members.
How it connects
Connects Razor views with view models, action methods, model directives, and view imports files.

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.