liveBook · Manning

Directive

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

A Razor directive is an instruction beginning with @ that controls compilation or behavior of a Razor file.

A Razor directive is an @-prefixed statement that changes how a Razor file is parsed or compiled. In Razor Pages, @page makes a .cshtml file routable; without it, the framework ignores the file for most purposes. section 17.2.1

Common directives connect a Razor view to its page model or make names available:

  • @page marks the file as a Razor Page. section 17.2.1
  • @model identifies the PageModel type used for binding and page-handler execution; it is technically optional. section 17.2.1
  • @using imports a namespace so its objects are available in the view. section 17.2.1

A routable Razor Page

Place these directives at the top of a .cshtml file:\n\n@page\n@model ToDoItemModel\n\nThe framework can route requests to the page and associate it with ToDoItemModel. It then binds marked properties and runs the appropriate handler. section 17.2.1

@page
@model ToDoItemModel

Use the compact listing to recognize the two directives that establish a Razor Page and its PageModel. section 17.2.1

Shared directives belong in _ViewImports.cshtml, which applies them to views and subfolders. Use it for directives such as @using or @addTagHelper, not arbitrary C#. Use _ViewStart.cshtml for shared Razor code such as assigning a default Layout. section 17.4.4

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

How deep it goes
Explains directive effects and placement, but stops short of detailed compiler internals.
Examples
Uses @page, @model, @using, @addTagHelper, _ViewImports.cshtml, and _ViewStart.cshtml examples.
What it assumes
Assumes familiarity with .cshtml files and introduces directive roles, PageModels, view imports, and view starts.
What you can do after
Apply it via ASP.NET Core Razor Pages to route views, associate PageModels, import namespaces, and share view settings.
How it connects
Links Razor directives with Razor Pages, PageModel, page handlers, namespaces, Tag Helpers, layouts, and partial views.

Also explained in

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