Razor syntax builds an HTML response from a template that mixes ordinary HTML with C#. A Razor view is a .cshtml file: its static markup is copied into the response, while its C# can insert values or choose which markup to render. The browser receives HTML, not the template’s C# code. section 17.2.2
In Razor Pages, @page makes a .cshtml file a routable page, and @model names its associated PageModel. A page handler can prepare data as public PageModel properties; the view reads those properties through Model and decides how to display them. Keep application logic in the handler and its services rather than building HTML strings there. section 17.2.1 section 13.4.3
Use @ to move from markup into C#:
- @Model.ExistingUsers.Count writes a value into the HTML response. Use @(...) to mark the boundaries of an expression containing whitespace; expressions do not need a trailing semicolon. section 17.1 section 17.3.1
- @{ ... } runs C# without writing its result. Statements inside the block need semicolons; for example, @{ ViewData["Title"] = "Home Page"; } sets a value for later use. section 17.3.1
- @if and @foreach conditionally render markup or repeat it for a collection. Keep templates simple even though .cshtml files can be compiled into C# with more complex behavior. section 17.3.2 section 17.3
- Use @@ when the output needs a literal @ character. section 17.3.1
Listing 17.6 Razor template for rendering a ToDoItemViewModel
@page @model ToDoItemModel #1 <div> @if (Model.IsComplete) { #2 <strong>Well done, you’re all done!</strong> #2 } #2 else { <strong>The following tasks remain:</strong> <ul> @foreach (var task in Model.Tasks) #3 { <li>@task</li> #4 } </ul> } </div> #1 The @model directive indicates the type of PageModel in Model. #2 The if control structure checks the value of the PageModel’s IsComplete property at runtime. #3 The foreach structure will generate the <li> elements once for each task in Model.Tasks. #4 A Razor expression is used to write the task to the HTML output.
The to-do template checks Model.IsComplete, then either displays a completion message or uses @foreach to produce one list item per remaining task. @task writes each task’s value. section 17.3.2
Razor HTML-encodes values written by C# expressions. Thus a task containing <strong>Check oil</strong> appears as text instead of becoming markup. Html.Raw bypasses that protection; avoid it for user-provided values because they could inject malicious content. section 17.3.3
For shared markup, a layout places a child view’s content at @RenderBody(); a view can pass a title to the layout through ViewData. Partial views reuse smaller snippets, while Tag Helpers bind models to HTML elements. Layouts and partial views are templates, not routable Razor Pages, so they do not need @page. Razor views also serve MVC controllers, not only Razor Pages. section 17.4.1 section 17.5 section 19.2
