liveBook · Manning

Page directive

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

The @page directive is a Razor directive that marks a .cshtml file as a routable Razor Page.

The @page directive marks a .cshtml file as a routable Razor Page. It must be the first line; without it, ASP.NET Core ignores the file as a Razor Page and does not expose an endpoint. section 13.1.3 section 13.5

Use the directive to control how a Razor Page is reached:

  • Write @page alone to use the default route derived from the file’s location, such as Pages/Privacy.cshtml mapping to /Privacy. section 13.1.3 section 13.5
  • Append a relative route template, such as @page "Extra" or @page "{category}/{name}", to add segments or route parameters. section 14.4.1
  • Start the template with / to replace the default route completely, such as @page "/checkout". section 14.4.2

A minimal Razor Page

Place the directive first, then associate the view with its PageModel and render ordinary HTML. The page below uses the default /Privacy route and displays a title from ViewData. section 13.1.3

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 listing, including the directive, PageModel association, C# block, and dynamic HTML. section 13.1.3

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

How deep it goes
Explains placement, default routing, appended segments, parameters, and replacement templates, while deferring additional-route preservation.
Examples
Uses Privacy.cshtml, Extra, category and name parameters, and checkout route templates.
What it assumes
Assumes familiarity with .cshtml files and introduces Razor Page registration alongside HTML, C#, and PageModel association.
What you can do after
Operate/configure Razor Page endpoints by registering pages and defining default, relative, or absolute route templates.
How it connects
Connects Razor Pages with routing, PageModel, page handlers, Razor views, and code-behind.

Also explained in

Compare how 2 books explain page 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.