Razor syntax basics
Razor is the markup syntax used in MVC views. It switches between HTML and C# with the @ symbol. This lesson covers expressions, code blocks, conditions, loops, comments, and how Razor keeps output safe by encoding it.
- @Model.NameImplicit expression: writes a value, HTML-encoded
- @(price * qty)Explicit expression: use parentheses for operators
- @{ var x = 1; }Code block: runs C# without writing output
- @if / @foreachControl flow that mixes C# and HTML
- @* comment *@Razor comment, never sent to the browser
- @model, @using, @injectDirectives that configure the view
The idea in plain words
Razor lets you write HTML and drop into C# whenever you need a value or some control flow. The @ symbol is the switch. Anything after @ is treated as C# until Razor can tell the expression has ended, and then it goes back to HTML. Files that use Razor in MVC have the .cshtml extension.
Razor is compiled into C# classes, so mistakes in your C# code are caught when the project builds or when the view first compiles. That makes views much safer than string templates.
Expressions and code blocks
An implicit expression is @ followed by a C# expression, such as @Model.Name or @DateTime.Now. When the expression contains spaces or operators, wrap it in parentheses to make it explicit, for example @(price * quantity). A code block in @{ } runs statements without writing anything to the page, which is handy for declaring a local variable.
To show a literal @ sign, write it twice: @@. Email addresses are recognized automatically, so [email protected] is printed as text.
- @Model.Title writes a value.
- @(a + b) writes the result of an expression with operators.
- @{ var total = 10; } runs code without output.
- @* comment *@ is a Razor comment and never reaches the browser.
Example
This view uses a code block, an explicit expression, a condition and a loop. Inside a code block, Razor recognizes HTML tags and switches back to markup automatically.
@model List<CartItem>
@{
ViewData["Title"] = "Your cart";
var total = Model.Sum(i => i.Price * i.Quantity);
}
<h1>@ViewData["Title"]</h1>
@if (Model.Count == 0)
{
<p>Your cart is empty.</p>
}
else
{
<table>
@foreach (var item in Model)
{
<tr>
<td>@item.Name</td>
<td>@item.Quantity</td>
<td>@((item.Price * item.Quantity).ToString("C"))</td>
</tr>
}
</table>
<p>Total: @total.ToString("C")</p>
}
@* Razor comments are removed from the output *@Directives
Directives are keywords after @ that change how the view is compiled. You will use a handful of them all the time. Shared ones usually go in _ViewImports.cshtml so every view gets them.
@model ProductViewModel @* the type of Model *@
@using MyShop.Models @* import a namespace *@
@inject IClock Clock @* get a service from DI *@
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<p>Rendered at @Clock.Now</p>Common mistakes
Most Razor errors are about where an expression ends or about encoding.
- Writing @item.Price * item.Quantity without parentheses, which prints the price followed by the literal text * item.Quantity.
- Using Html.Raw to print user data, which disables encoding and allows script injection.
- Putting large amounts of logic in @{ } blocks. Move it to the controller or a view model property.
- Using an HTML comment instead of a Razor comment and leaking notes to the browser.
Going further
Razor also supports @section for content that a layout places in a named spot, and @functions for small helper methods inside a view. Templated Razor delegates and Tag Helpers build on the same syntax. The layouts and Tag Helpers lessons later in this course show those in action.
Interview question
How does Razor protect against cross-site scripting, and how can a developer accidentally turn that protection off?
Razor HTML-encodes the result of every @ expression, so characters like < and > are written as entities and a script tag in user input is shown as text instead of running. Calling Html.Raw, or returning an HtmlString built from user input, skips that encoding and can allow script injection, so it should only be used for trusted, already-sanitized HTML.
Want the full details? Read the official Microsoft documentation for this topic.