Razor Views & Syntax
Razor is the template language ASP.NET Core uses to produce HTML. A Razor file (.cshtml) is mostly ordinary HTML with C# mixed in after an @ sign. At build time each view is compiled into a C# class, so mistakes in your C# show up as compiler errors, and rendering is fast.
In an MVC app a controller action prepares data (the model) and hands it to a view:
public class ProductsController(IProductStore store) : Controller // Controller, not ControllerBase
{
public IActionResult Index()
{
var products = store.All();
ViewData["Title"] = "Our products";
return View(products); // renders Views/Products/Index.cshtml
}
}View() with no name looks for Views/<Controller>/<Action>.cshtml, then falls back to Views/Shared/<Action>.cshtml.
Razor syntax essentials
@model IReadOnlyList<Product>
<h1>@ViewData["Title"]</h1>
<p>We have @Model.Count products. Cheapest: @(Model.Min(p => p.Price).ToString("C"))</p>
@if (Model.Count == 0)
{
<p>Nothing for sale yet.</p>
}
else
{
<ul>
@foreach (var p in Model)
{
<li class="@(p.Stock == 0 ? "sold-out" : null)">
@p.Name — @p.Price.ToString("0.00")
@if (p.Stock == 0) { <strong>(sold out)</strong> }
</li>
}
</ul>
}
@{
var year = 2026; // a code block: plain C# statements
}
<footer>© @year Demo Shop · contact@@demo.shop</footer>| Syntax | Meaning |
|---|---|
@model T |
Declares the type of Model for this view |
@expr |
Implicit expression — writes the value, HTML-encoded |
@(a + b) |
Explicit expression — needed when the expression contains spaces or operators |
@{ ... } |
Code block with C# statements |
@if, @foreach, @switch, @using |
Control flow; inside braces you can return to HTML directly |
@* comment *@ |
Razor comment, not sent to the browser |
@@ |
A literal @ character |
@Html.Raw(x) |
Write x without encoding (only for trusted HTML!) |
A class attribute whose value is null is omitted entirely, so the sold-out class only appears where needed.
$ curl -s localhost:5000/products<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Our products - Demo Shop</title>
</head>
<body>
<main>
<h1>Our products</h1>
<p>We have 2 products. Cheapest: $19.50</p>
<ul>
<li>
Keyboard — 49.90
</li>
<li class="sold-out">
Mouse — 19.50
<strong>(sold out)</strong>
</li>
</ul>
<footer>© 2026 Demo Shop · contact@demo.shop</footer>
</main>
</body>
</html>
Encoding protects you
Every @value is HTML-encoded. If a user names a product <script>alert(1)</script>, the browser shows the text instead of running it. Razor uses the same idea as WebUtility.HtmlEncode:
using System;
using System.Net;
string userInput = "<script>alert('hi')</script> & \"friends\"";
Console.WriteLine("Encoded (what @value writes):");
Console.WriteLine(WebUtility.HtmlEncode(userInput));
Console.WriteLine("Raw (what @Html.Raw writes):");
Console.WriteLine(userInput);Encoded (what @value writes):
<script>alert('hi')</script> & "friends"
Raw (what @Html.Raw writes):
<script>alert('hi')</script> & "friends"
Note: Only the
@values are encoded — the literal markup you type in the.cshtmlfile is copied as-is. ASP.NET Core's real encoder (HtmlEncoder.Default) is also a little stricter thanWebUtility: it encodes most non-ASCII characters too, so a value likeCaféis written asCafé. The browser displays both forms identically.
Layouts, sections and partials
Most pages share a header and footer. Put them in a layout, Views/Shared/_Layout.cshtml, and call @RenderBody() where each page's content goes:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewData["Title"] - Demo Shop</title>
</head>
<body>
<main>
@RenderBody()
</main>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>A page can fill an optional section with @section Scripts { <script src="~/js/cart.js"></script> }. Small reusable fragments go in partial views (_ProductCard.cshtml) rendered with <partial name="_ProductCard" model="p" />.
Two special files apply to every view in their folder and below:
| File | Purpose |
|---|---|
_ViewStart.cshtml |
Code run before each view — usually @{ Layout = "_Layout"; } |
_ViewImports.cshtml |
Shared @using directives and @addTagHelper registrations |
Conceptually, rendering a view is "run the page to produce a body string, then run the layout with that string in place of RenderBody()":
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
var products = new List<(string Name, decimal Price)> { ("Keyboard", 49.90m), ("Mouse <USB>", 19.50m) };
string body = IndexView(products);
Console.WriteLine(Layout("Our products", body));
static string IndexView(List<(string Name, decimal Price)> model)
{
var sb = new StringBuilder();
sb.AppendLine("<ul>");
foreach (var p in model)
sb.AppendLine(quot; <li>{WebUtility.HtmlEncode(p.Name)} - {p.Price:0.00}</li>");
sb.Append("</ul>");
return sb.ToString();
}
static string Layout(string title, string renderBody) =>
quot;<html><head><title>{WebUtility.HtmlEncode(title)}</title></head>\n<body>\n{renderBody}\n</body></html>";<html><head><title>Our products</title></head>
<body>
<ul>
<li>Keyboard - 49.90</li>
<li>Mouse <USB> - 19.50</li>
</ul>
</body></html>
Passing data to a view
| Mechanism | Typed? | Use for |
|---|---|---|
View(model) + @model |
Yes | The main data of the page — prefer this |
ViewData["Key"] |
No (dictionary) | Small extras such as the page title |
ViewBag.Key |
No (dynamic wrapper over ViewData) |
Same as ViewData, different syntax |
TempData["Key"] |
No | A message that survives one redirect ("Saved!") |
Tip: Create a dedicated view model class per page (
ProductListViewModel) instead of stuffing values intoViewBag. You get IntelliSense, compile-time checking and a clear contract between controller and view.
Test yourself
Which Razor syntax writes a value WITHOUT HTML-encoding it?
- @value
- @(value)
- @Html.Raw(value)
- @{ value }
What does @RenderBody() do in a layout?
- Inserts the output of the view being rendered
- Renders the
<body>tag - Renders all partial views
- Re-runs the controller action
How do you write a literal email address like me@site.com safely in Razor?
- me\@site.com
- me@@site.com
- @"me@site.com"
- It is impossible