Introduction
Razor is a template syntax for .NET: a file is ordinary HTML, and an @ sign switches into C# (or Visual Basic) to write a value, run a loop, declare a member or give an instruction to the compiler. The Razor compiler turns the file into a C# class; for a view the class writes the HTML to the response, for a Blazor component it builds a render tree. Nothing is interpreted at run time from the text.
Three file extensions carry it. .razor is a Blazor component, .cshtml is an ASP.NET Core or MVC view, layout, partial view or Razor Page written in C#, and .vbhtml is the same for Visual Basic in the older ASP.NET Web Pages and MVC. They share the idea and most of the rules, but have different sets of directives, so they are described side by side here, with the differences marked.
@page "/counter"
@rendermode InteractiveServer
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount() => currentCount++;
}
@code block.@model IEnumerable<Product>
@{
ViewData["Title"] = "Products";
}
<ul>
@foreach (var p in Model)
{
<li>@p.Name: @p.Price.ToString("C")</li>
}
</ul>
<p>Questions: sales@@contoso.com</p>
The three formats
| Extension | Host | Code language | Directives |
|---|---|---|---|
.razor | Blazor (server, WebAssembly, web app) | C# | @page @code @functions @inject @layout @typeparam @rendermode @preservewhitespace @attribute @implements @inherits @namespace @using, the tag helper directives and @documentation |
.cshtml | ASP.NET Core MVC and Razor Pages; ASP.NET MVC 3 to 5 and Web Pages | C# | @model @page @inject @functions @section @inherits @implements @attribute @namespace @using, the tag helper directives and @documentation; older hosts add @helper @layout @sessionstate |
.vbhtml | ASP.NET MVC 3 to 5 and Web Pages | Visual Basic | @Code @Functions @Section @Helper @Imports @Inherits @ModelType @Layout @SessionState @Option, ended by End ... lines |
Import files hold directives that apply to every file below them: _Imports.razor for components and _ViewImports.cshtml for views. _ViewStart.cshtml holds code that runs before each view. See File kinds and conventions.
Syntax at a glance
| Written | Meaning | Page |
|---|---|---|
@name.Member(1)[2] | Implicit expression: a member chain, ended by a space or any other character | Transitions and expressions |
@(a + b) | Explicit expression: anything up to the matching parenthesis | Transitions and expressions |
@{ ... } | Code block: statements that write nothing by themselves | Code blocks and control flow |
@if (x) { ... } else { ... }, @foreach, @for, @while, @do, @switch, @try, @lock, @using (...) | Control flow; the braces hold markup and code | Code blocks and control flow |
<p> inside a block, <text>...</text>, @:line, @<li>...</li> | Back to markup: a tag, a tag-less region, a rest of line, an inline template | Code blocks and control flow |
@page "/x", @model T, @code { ... } | Directives: instructions to the compiler | Directives |
@* ... *@, @@, a@b.com | Razor comment, escaped at sign, an email address that is not code | Comments, escaping and whitespace |
<Counter Step="2" />, @bind, @onclick, @key, @ref | A component and the directive attributes on elements and components | Components, Directive attributes |
<input asp-for="Name" /> | A tag helper: an element or attribute that server code handles | Tag helpers |
What the viewer shows
Dropping a file with one of the three extensions shows its text coloured: markup through the HTML colouring, code through the C# (or Visual Basic) colouring, and Razor's own words (transitions, directives, directive attributes, @* comments, escapes) in the directive colour. Component tags are coloured as types. A .cshtml file that holds Visual Basic Razor is read as Visual Basic. Two more tabs list what the scanner found: the Outline (directives, code blocks, sections, components, tag helper uses and directive attributes, each with its line) and the Problems (unbalanced braces, parentheses and tags, unterminated comments and strings, a misplaced or repeated directive, a directive that expects something else, @ followed by a character that cannot start code). Every problem is listed, in pages. Nothing is compiled or evaluated; the scanner follows the rules of the real parser, which the following pages describe.
Not described
Known, not yet covered
- Reference: the code the compiler generates (the intermediate representation,
BuildRenderTreecalls, theExecuteAsyncmethod of a view) is mentioned, not described. The source is public (Microsoft.CodeAnalysis.Razor.Compilerin dotnet/roslyn). - Reference: which tag helpers and components a given project has comes from compiled assemblies, not from the text; the pages list the built-in ones the text can show (
asp-*attributes,partial,environment,cache,component) and the event attributes of Blazor, not every tag helper of every package. - Reference: the legacy ASP.NET Web Pages helpers (
@helperdefinitions,WebPagemethods,@sessionstate) and the Visual Basic parser are described from the source ofSystem.Web.Razoronly; the .NET Framework documentation pages were not read. - Viewer: the scanner does not know which names are components or tag helpers in a project; a component is any element whose name starts with a capital letter or has a dot, and tag helpers are recognised by
asp-attributes and a few built-in element names. - Viewer: the file name is not used:
_Imports.razorand_ViewImports.cshtmlare read like any other file, so a directive that is not allowed in an imports file (@code,@pagein_ViewImports.cshtml) is not reported. - Viewer: C# inside a code block is coloured piece by piece (each stretch between two bits of markup separately), so a C# construct that spans markup, such as a raw string interrupted by a template, loses its colour. The C# is not parsed; unbalanced C# other than braces, parentheses and brackets is not reported.
- Viewer: HTML is coloured by the HTML colouring with the code blanked out;
@sectionbodies in Visual Basic and nested Razor in script and style blocks use the same rules as markup.
Unknown
- Reference: none of the examples was compiled: there is no .NET SDK on this Mac (
dotnetis not installed). The examples follow the documentation and the parser source, and the page test checks their structure with the same scanner. - Reference: the exact release of each directive and language-version change is taken from the version table of the compiler (language versions 1.0 to 12.0) and the documentation's version notes; where neither names a release, the pages do not give one.
Also used for
- Razor view (Visual Basic) – A Visual Basic view of ASP.NET MVC and Web Pages.
- Razor view or page – An ASP.NET Core or MVC view, layout, partial view or Razor Page in C#.
Links
Software
- Visual Studio – the IDE with the Razor editor, formatting and tag helper completion (Windows, macOS)
- Visual Studio Code – edits Razor with the C# Dev Kit (Windows, macOS, Linux)
- JetBrains Rider – .NET IDE with Razor support (Windows, macOS, Linux)
- ASP.NET Core – the web framework that compiles views, pages and components (Windows, macOS, Linux)
Developers
- dotnet/roslyn, src/Razor – the Razor compiler, parser and tooling (C#)
- dotnet/blazor-samples – sample Blazor apps with many components (C#)
- AspNetWebStack – System.Web.Razor, the original parser for ASP.NET Web Pages and MVC, including the Visual Basic one (C#)
Reference
- Razor syntax reference for ASP.NET Core – Microsoft's reference for the syntax
- ASP.NET Core Razor components – Microsoft's documentation of component syntax
- Tag Helpers in ASP.NET Core – tag helper scope and syntax
- C# source files – the language of the code parts (on this site)
- Visual Basic source files – the language of
.vbhtmlcode (on this site) - HTML – the language of the markup parts (on this site)