9.4 — Razor Syntax, Layouts, _ViewStart and _ViewImports¶
← Roadmap · Section: 9. MVC, Razor Pages and Views Prev: 9.3 Action results · Next: 9.5 Partials, view components and tag helpers
Markers: ⭐ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Razor is the template syntax that mixes C# into HTML. The @ symbol switches from HTML into
C# and back again.
_Layout.cshtmlis the shared page shell — header, navigation, footer — with@RenderBody()where the page content goes._ViewStart.cshtmlruns before every view and is where the layout is chosen._ViewImports.cshtmlholds shared@usingand@addTagHelperdirectives so every view does not repeat them.- ⚠️ Razor HTML-encodes everything by default, which is what prevents XSS.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Razor | a template syntax | Mixes C# into HTML. Files end in .cshtml. |
@ |
the transition character | Switches from HTML into C#. |
@{ } |
a code block | Several statements of C#, producing no output by itself. |
| Layout | a shared page shell | _Layout.cshtml. Wraps every view that uses it. |
@RenderBody() |
a method | Where the view's content is inserted into the layout. |
@RenderSection() |
a method | Renders a named section a view can optionally fill. |
@section |
a directive | Defines content for a named section in the layout. |
_ViewStart.cshtml |
a special file | Code that runs before every view in that folder and below. |
_ViewImports.cshtml |
a special file | Shared @using, @model, @inject and tag helper registrations. |
@model |
a directive | Declares the type of Model for this view. |
@inject |
a directive | Injects a service into the view. |
| HTML encoding | automatic escaping | Razor escapes output so <script> renders as text, not code. |
HtmlString / Html.Raw |
a class / method | Renders unencoded. ⚠️ The XSS risk. |
The concept¶
The @ symbol¶
Razor is HTML until you write @, then it is C# until the expression ends:
Razor works out where the C# stops — it stops at the end of the expression, so @Model.Name picks
up the property and the following space returns to HTML.
For anything more complex, use parentheses:
And a code block for several statements:
@{
var total = Model.Lines.Sum(l => l.Price * l.Quantity);
var isLarge = total > 1000;
}
<p>Total: @total</p>
A picture: a bilingual document. Most of it is written in one language, and the @ is a
marker saying "the next bit is in the other language". Razor's job is knowing where to switch
back.
⚠️ Everything is HTML-encoded¶
This is the security-relevant part:
@* If Model.Comment is: <script>alert('xss')</script> *@
<p>@Model.Comment</p>
@* Renders as literal text, NOT executed:
<p><script>alert('xss')</script></p> *@
Razor escapes output automatically. That default is what makes Razor safe against cross-site scripting, and it is why XSS in an ASP.NET Core app almost always comes from deliberately bypassing it (17.3).
The bypasses:
⚠️ Only use those on content you generated or have sanitised. Rendering user-supplied HTML raw is the single most common XSS hole in a Razor application. If you must accept HTML — a rich text editor — sanitise it server-side with a library like HtmlSanitizer first.
How it works¶
The simple version — syntax¶
@* A Razor comment — not sent to the browser, unlike an HTML comment *@
@model OrderDetailsViewModel @* the model type for this view *@
<h1>@Model.Reference</h1>
@if (Model.CanCancel)
{
<button>Cancel</button>
}
else
{
<p>This order cannot be cancelled.</p>
}
<ul>
@foreach (var line in Model.Lines)
{
<li>@line.Product — @line.Quantity × @line.Price.ToString("C")</li>
}
</ul>
@{
var statusClass = Model.Status switch
{
"Shipped" => "badge-success",
"Cancelled" => "badge-danger",
_ => "badge-secondary"
};
}
<span class="@statusClass">@Model.Status</span>
⚠️ A Razor comment @* *@ is removed at render time; an HTML comment <!-- --> is sent to the
browser. Putting anything sensitive in an HTML comment publishes it.
Escaping an email address:
Layouts¶
A layout is the shell every page shares:
@* Views/Shared/_Layout.cshtml *@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] — My Shop</title>
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
@await RenderSectionAsync("Styles", required: false)
</head>
<body>
<header>
<nav>
<a asp-controller="Home" asp-action="Index">Home</a>
<a asp-controller="Orders" asp-action="Index">Orders</a>
</nav>
</header>
<main>
@RenderBody() @* ← the view's content goes here *@
</main>
<footer>© @DateTime.UtcNow.Year</footer>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
Two things worth noting.
asp-append-version="true" adds a content hash to the URL, so browsers cache aggressively and
still pick up changes (4.10).
required: false on sections means a view that does not define them still renders. With
required: true, a view missing that section throws.
Sections¶
A view fills a named section:
@model OrderDetailsViewModel
@{
ViewData["Title"] = $"Order {Model.Reference}";
}
<h1>Order @Model.Reference</h1>
@section Scripts {
<script src="~/js/order-details.js" asp-append-version="true"></script>
}
Sections let a page inject content into a specific place in the layout — scripts at the bottom,
extra stylesheets in the head — rather than everything landing in @RenderBody().
⚠️ Sections do not flow into partials. A partial view cannot define a section for the layout, because partials render independently. That is a common frustration, and view components have the same limitation (9.5).
_ViewStart.cshtml¶
Runs before every view in its folder and below:
That one file is why individual views do not each set their layout. It cascades, so
Areas/Admin/Views/_ViewStart.cshtml can override it for that area
(8.8).
Opting out for a specific view:
_ViewImports.cshtml¶
Shared directives, so every view does not repeat them:
@* Views/_ViewImports.cshtml *@
@using MyApp
@using MyApp.Models
@using MyApp.ViewModels
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@inject IOptions<AppOptions> AppOptions
⚠️ @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers is what makes tag helpers work.
Without it, asp-controller and asp-for are inert HTML attributes rendered literally into the
page — the form does nothing and there is no error. It is the most common "why is my tag helper
not working" cause (9.5).
Both files cascade, so a folder-level _ViewImports.cshtml adds to the root one rather than
replacing it.
How it actually works — view discovery¶
return View() searches, in order:
With areas, two more paths come first (8.8):
⚠️ The error message lists every path it searched, which makes this one of the more pleasant failures to debug — it tells you exactly where it looked.
⚠️ On Linux, file names are case-sensitive. Views/Orders/details.cshtml is not found when the
action is Details. That works on Windows and fails on deployment, which is a genuinely annoying
class of bug (7.2 has the same issue for config
files).
The deeper detail — @inject and logic in views¶
You can inject a service directly into a view:
@inject IOptions<AppOptions> Options
@inject IFeatureManager Features
@if (await Features.IsEnabledAsync("NewCheckout"))
{
<partial name="_NewCheckout" />
}
⚠️ Use this sparingly. It is right for cross-cutting things a layout needs — feature flags, localisation, configuration — and wrong for fetching data:
@* ✗ The view is now querying the database *@
@inject IOrderService Orders
@{
var orders = await Orders.ListAsync();
}
That makes the view untestable, hides a database call inside rendering, and bypasses the controller entirely. Data belongs on the ViewModel (9.8); a view component is the right tool when a fragment genuinely needs its own data (9.5).
⚠️ The same applies to logic. A view with a business rule in it cannot be unit tested:
@* ✗ untestable *@
@if (Model.Status == "Pending" && Model.CreatedAt > DateTime.UtcNow.AddDays(-30))
@* ✓ the ViewModel decided *@
@if (Model.CanCancel)
Code¶
A complete, realistic set:
@* Views/_ViewImports.cshtml *@
@using MyApp.ViewModels
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@* Views/Shared/_Layout.cshtml *@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] — My Shop</title>
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
@await RenderSectionAsync("Styles", required: false)
</head>
<body>
<partial name="_Navigation" />
<main class="container">
@* Flash messages surviving a redirect — see 9.6 *@
@if (TempData["Success"] is string success)
{
<div class="alert alert-success">@success</div>
}
@if (TempData["Error"] is string error)
{
<div class="alert alert-danger">@error</div>
}
@RenderBody()
</main>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
@* Views/Orders/Details.cshtml *@
@model OrderDetailsViewModel
@{
ViewData["Title"] = $"Order {Model.Reference}";
}
<h1>Order @Model.Reference</h1>
<p class="text-muted">Placed @Model.CreatedAt.ToString("d MMMM yyyy")</p>
<span class="badge @Model.StatusCssClass">@Model.StatusText</span>
<table class="table">
<thead>
<tr><th>Product</th><th>Quantity</th><th>Price</th></tr>
</thead>
<tbody>
@foreach (var line in Model.Lines)
{
<tr>
<td>@line.ProductName</td>
<td>@line.Quantity</td>
<td>@line.LineTotal.ToString("C")</td>
</tr>
}
</tbody>
<tfoot>
<tr><th colspan="2">Total</th><th>@Model.Total.ToString("C")</th></tr>
</tfoot>
</table>
@if (Model.CanCancel)
{
<form asp-action="Cancel" asp-route-id="@Model.Id" method="post">
<button type="submit" class="btn btn-danger">Cancel this order</button>
</form>
}
@section Scripts {
<script src="~/js/order-details.js" asp-append-version="true"></script>
}
Three things the view does not do, and that is the point: it does not decide whether
cancellation is allowed (Model.CanCancel), it does not choose the CSS class from a status string
(Model.StatusCssClass), and it does not query anything. All of that was decided before rendering
began.
Interview questions¶
Q: What are _ViewStart.cshtml and _ViewImports.cshtml for?
_ViewStart runs before every view in its folder and below, and it is where the layout is set —
which is why individual views do not each specify one. _ViewImports holds shared directives:
@using statements, @inject declarations, and crucially the @addTagHelper line that enables
tag helpers. Both cascade, so a folder-level file adds to the root one rather than replacing it,
and an area can override the layout for just that area.
Q: How does Razor protect against XSS?
It HTML-encodes all output by default, so a comment containing a script tag renders as visible
text rather than executing. That default is why XSS in a Razor application almost always comes
from deliberately bypassing it with Html.Raw or HtmlString. Those exist for content you
generated yourself or have sanitised server-side — rendering user-supplied HTML raw is the most
common XSS hole in an ASP.NET Core app.
Q: What is the most common reason a tag helper does not work?
The @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers line is missing from _ViewImports.
Without it, attributes like asp-controller and asp-for are treated as ordinary HTML attributes
and rendered literally into the page, so the form posts nowhere and there is no error anywhere —
it just silently does not work. That silence is what makes it hard to diagnose the first time.
Q: Should you inject services into views?
Sparingly, and only for cross-cutting concerns a layout genuinely needs — feature flags, localisation, configuration. Injecting a data service and querying from a view is a mistake: it hides a database call inside rendering, makes the view untestable, and bypasses the controller. Data belongs on the ViewModel, prepared before rendering starts. If a fragment genuinely needs its own data independent of the page, a view component is the right tool.
Traps ⚠️¶
Html.RawandHtmlStringbypass encoding. The main XSS risk in Razor.@* *@is removed;<!-- -->is sent to the browser. Do not put anything sensitive in an HTML comment.- Missing
@addTagHelpermakes tag helpers render as literal attributes, silently. - View file names are case-sensitive on Linux. Works on Windows, 500s on deployment.
- Sections cannot be defined in partials or view components.
required: trueon a section throws if a view does not define it.- Logic in views is untestable. Put decisions on the ViewModel.
@injectfor data access hides queries inside rendering.@before an email address needs escaping as@@.
Related¶
- 9.5 Partials, view components and tag helpers — reusable fragments
- 9.6 ViewData, ViewBag and TempData —
ViewData["Title"] - 9.8 ViewModels — what the view should receive
- 9.1 The MVC pattern — keeping logic out of views
- 17.3 XSS — why encoding matters
- 8.8 Areas — per-area
_ViewStart - 4.10 Static files —
asp-append-version