TExcelTAD
Home › ASP.NET Core › Razor Views & Syntax

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:

csharp
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

cshtml
@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>&copy; @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.

bash · try it yourself
$ 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>&copy; 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:

csharp · try it yourself
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):
&lt;script&gt;alert(&#39;hi&#39;)&lt;/script&gt; &amp; &quot;friends&quot;
Raw (what @Html.Raw writes):
<script>alert('hi')</script> & "friends"

Note: Only the @ values are encoded — the literal markup you type in the .cshtml file is copied as-is. ASP.NET Core's real encoder (HtmlEncoder.Default) is also a little stricter than WebUtility: it encodes most non-ASCII characters too, so a value like Café is written as Caf&#xE9;. 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:

cshtml
<!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()":

csharp · try it yourself
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 &lt;USB&gt; - 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 into ViewBag. 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?

  1. @value
  2. @(value)
  3. @Html.Raw(value)
  4. @{ value }

What does @RenderBody() do in a layout?

  1. Inserts the output of the view being rendered
  2. Renders the <body> tag
  3. Renders all partial views
  4. Re-runs the controller action

How do you write a literal email address like me@site.com safely in Razor?

  1. me\@site.com
  2. me@@site.com
  3. @"me@site.com"
  4. It is impossible