Razor syntax overview
What is Razor?
Razor is a markup syntax for embedding .NET based code into webpages.
The Razor syntax consists of Razor markup, C# and HTML.
Files containing Razor generally have a .
cshtml
file extension.Razor is also found in Razor component files, with an extension of
.razor
Razor syntax is similar to the templating engines of various JavaScript single-page application (SPA) frameworks, such as Angular, React, VueJs, and Svelte.
Razor syntax
Razor supports C# and uses the
@
symbol to transition from HTML to C#.Razor evaluates C# expressions and renders them in the HTML output.
When an
@
symbol is followed by a Razor reserved keyword, it transitions into Razor-specific markup.
To escape an @
symbol in Razor markup, use a second @
symbol as shown below:
The code is rendered in HTML with a single @
symbol:
Implicit Razor expressions
Implicit Razor expressions start with @
followed by C# code:
With the exception of the C# await
keyword, implicit expressions must not contain spaces. If the C# statement has a clear ending, spaces can be intermingled:
Explicit Razor expressions
Explicit Razor expressions consist of an @
symbol with balanced parenthesis. To render last weeks' time, the following Razor markup is used:
Why we need paranthesis?
Razor expressions generally can't contain spaces. In the following code, one week is not subtracted from the current time!
The code renders the following HTML:
Hence, we need parenthesis to enclose the complete c# expression in such cases.
Raw HTML
Raw HTML
HtmlHelper.Raw
output isn't encoded but rendered as HTML markup.
The code renders the following HTML:
Razor code blocks
Razor code blocks start with @
and are enclosed by {}
. Unlike expressions, C# code inside code blocks isn't rendered.
The code renders the following HTML:
Implicit transitions
The default language in a code block is C#, but the Razor Page can transition back to HTML:
Explicit delimited transition
To define a subsection of a code block that should render HTML, surround the characters for rendering with the Razor <text>
tag:
Use this approach to render HTML that isn't surrounded by an HTML tag. Without an HTML or Razor tag, a Razor runtime error occurs.
Last updated