Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 52 ยท MVC, Controllers and Razor

Razor Views and Razor Pages Overview

Learn Razor syntax, automatic HTML encoding, layouts, partials, tag helpers, view components and Razor Pages handlers, with runnable stand-ins you can edit.

Not every web application returns JSON. Plenty of them return HTML: a shop, a blog, an admin panel. Writing HTML by gluing strings together in C# is slow and dangerous, so ASP.NET Core ships a template language called Razor. A Razor file is mostly plain HTML with small islands of C# that start with an @ sign. At build time the file is turned into a C# class, and at run time that class writes HTML to the response.

Razor shows up in two shapes. MVC views (.cshtml files rendered by a controller action, see Controllers and Actions) separate the controller from the template. Razor Pages put each page's template and its handler code side by side, keyed by URL. Both use the same Razor syntax, layouts, partials and tag helpers. This lesson is a tour of those shared ideas.

The live runner compiles one C# file and has no Razor compiler, no .cshtml files and no view compilation. So the real Razor code in this lesson is read-only, and every runnable example is a small hand-written stand-in that shows the mechanism (encoding, layouts, partials, handler selection) with plain C#. The stand-ins are honest simplifications, not the real engine.

What a Razor file looks like

Here is a complete view. The @model line declares what data the page receives, @Model reads it, and @foreach loops.

HTML
@model ProductListModel
@{
    ViewData["Title"] = "Products";
}

<h1>@Model.Heading</h1>

@if (Model.Items.Count == 0)
{
    <p>Nothing here yet.</p>
}
else
{
    <ul>
    @foreach (var item in Model.Items)
    {
        <li>@item.Name costs @item.Price.ToString("C")</li>
    }
    </ul>
}

<p>Total items: @(Model.Items.Count * 1)</p>
<p>Write an at sign twice to show it: user@@example.com</p>

The rules fit on one hand:

  • @expression writes a value. @Model.Name and @item.Price.ToString("C") work, and @(a + b) uses parentheses for anything with spaces or operators.
  • @{ ... } is a code block for statements that write nothing.
  • @if, @foreach, @for, @switch, @using and @try are control constructs; the braces contain a mix of HTML and C#.
  • @@ is a literal @. Razor is smart enough not to treat [email protected] as code, but doubling is the safe way.
  • @* comment *@ is a Razor comment that never reaches the browser.

Razor parses markup and code together. When a line inside a code block starts with an HTML tag, Razor switches back to markup mode on its own; for a bare line of text, use @: or <text>.

flowchart LR
    A["Index.cshtml"] --> B["Razor compiler<br/>(build time)"]
    B --> C["generated C# class"]
    C --> D["compiled into the app"]
    D --> E["ExecuteAsync writes<br/>HTML to the response"]

A .cshtml file never runs as text: it becomes a normal C# class that writes the page.

Output is encoded for you

The most important property of Razor is automatic HTML encoding. Anything you write with @ passes through an HtmlEncoder, so < becomes &lt; and a user's <script> tag shows up as harmless text instead of running. This is your main defense against cross-site scripting (Web Security Essentials goes deeper).

If you really have trusted HTML, you wrap it in an IHtmlContent such as HtmlString (or call Html.Raw(...)), and Razor writes it untouched. The generated code does roughly what the helper below does.

C# How Razor encodes output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Plain strings are encoded, an HtmlString is passed through, numbers are converted with their ToString, and null writes nothing. The rule to remember: never use Html.Raw on anything a user could have typed.

Layouts, sections and partials

A site has a shared frame: header, navigation, footer. A layout holds that frame once. Each view fills in the middle.

HTML
@* Views/Shared/_Layout.cshtml *@
<!DOCTYPE html>
<html lang="en">
<head>
    <title>@ViewData["Title"] - My Shop</title>
    @await RenderSectionAsync("Head", required: false)
</head>
<body>
    <nav>...</nav>
    <main>
        @RenderBody()
    </main>
    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>

@RenderBody() is the hole the view's content goes into. A section is a named hole: the view declares @section Scripts { ... } and the layout decides where it appears. A file called _ViewStart.cshtml sets Layout = "_Layout"; for every view in its folder, and _ViewImports.cshtml holds shared @using and @addTagHelper lines, so you do not repeat them.

flowchart TD
    V["Product view<br/>(fills RenderBody)"] --> L["_Layout.cshtml<br/>(header, nav, footer)"]
    S["@section Scripts"] --> L
    L --> H["one complete HTML page"]

The view renders first, then the layout wraps it and places the sections.

A partial view is a reusable fragment, such as a product card used on three pages. In a view you write <partial name="_ProductCard" model="item" />. Partials have no layout of their own; they simply return HTML to be embedded.

The next stand-in builds the same ideas from strings: a layout with a body hole and a named section, plus a partial rendered once per item. It encodes every value, so you can see that layouts and partials do not weaken the encoding rule.

C# A tiny layout, section and partial engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the output: the layout supplies <html>, the title and the nav, the view supplies the list, and the hostile product name appears as &lt;b&gt;Hacker&lt;/b&gt; Tee. The real engine does this with compiled code instead of string replacement, but the shape (view first, layout wraps, sections placed by name) is the same.

Tag helpers and HTML helpers

Razor helps you generate links and forms without hard-coding URLs. Tag helpers look like ordinary HTML attributes that the server rewrites:

HTML
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<a asp-controller="Products" asp-action="Details" asp-route-id="@item.Id">@item.Name</a>

<form asp-action="Create" method="post">
    <label asp-for="Name"></label>
    <input asp-for="Name" class="form-control" />
    <span asp-validation-for="Name"></span>
    <button type="submit">Save</button>
</form>

The <a> becomes <a href="/Products/Details/7">, built from the routing table, so when you rename a route the links follow. <input asp-for="Name"> generates the right name, id and value attributes and the validation attributes from your data annotations, and <form method="post"> automatically gets a hidden anti-forgery token. Because tag helpers are HTML-first, designers and editors can read them. Older HTML helpers (@Html.TextBoxFor(...)) do the same job with method calls and are still supported.

View components

A partial view only receives the model you pass. When a fragment needs its own logic and data, such as a shopping-cart badge that loads the cart from a service, use a view component. It is a class with an InvokeAsync method and a matching view, and it takes part in dependency injection:

C#
public class CartBadgeViewComponent(ICartService carts) : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        int count = await carts.CountForCurrentUserAsync();
        return View(count);
    }
}

In a view you place it with <vc:cart-badge></vc:cart-badge> or @await Component.InvokeAsync("CartBadge"). Think of it as a small controller plus view that you can drop into any layout.

Razor Pages: a page and its handler together

With MVC, one feature is spread over a controller, a view and sometimes a model folder. Razor Pages keep the template and its code together and use the file path as the URL. Pages/Products/Index.cshtml answers /Products, and its companion class holds the handlers:

HTML
@page
@model IndexModel

<h1>Products</h1>
<form method="post">
    <input asp-for="NewName" />
    <button>Add</button>
    <button asp-page-handler="Clear">Clear all</button>
</form>
C#
public class IndexModel(IProductStore store) : PageModel
{
    public IReadOnlyList<Product> Products { get; private set; } = [];

    [BindProperty]
    public string NewName { get; set; } = "";

    public void OnGet() => Products = store.All();

    public IActionResult OnPost()
    {
        store.Add(NewName);
        return RedirectToPage();
    }

    public IActionResult OnPostClear()
    {
        store.Clear();
        return RedirectToPage();
    }
}

The @page directive is what turns a .cshtml file into a page with a route. A handler is a method named On + HTTP method + optional name, with an optional Async suffix: OnGet, OnPostAsync, OnPostClear. The framework picks one from the request method and the handler query-string value, so POST /Products?handler=Clear runs OnPostClear. [BindProperty] copies posted form values onto properties, which are then available in the handler and the view.

Here is the handler-selection rule as a runnable stand-in, wired into a real Kestrel app. A reflection-based dispatcher finds OnGet, OnPost and OnPostDelete methods by name, the same naming convention Razor Pages uses.

C# Selecting a page handler by name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The output shows OnGet, OnPost and OnPostDelete being chosen by request method and handler name, and an unsupported method answering 405. The real framework adds model binding, anti-forgery validation and rendering of the .cshtml file after the handler returns.

Which one should you choose?

  • Razor Pages is the simplest fit for page-focused sites, forms and admin screens: one folder per feature, little ceremony.
  • MVC suits larger apps with many ways to reach the same logic, or when the same controllers also serve an API. See the C# tutorial on MVC and Razor for a language-side view.
  • Minimal APIs (this tutorial so far) are the best fit for JSON services.
  • Blazor, the topic of the next lesson, builds interactive pages out of C# components instead of request/response templates.

All of them can live in one application and share middleware, dependency injection and authentication.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to a .cshtml file before it can serve a request?

    The Razor compiler turns each view into a C# class. At run time that class's code writes the markup and the evaluated expressions to the response.
  2. 2. A user submits the text <script>alert(1)</script> and your view writes it with @Model.Comment. What does the browser receive?

    Razor HTML-encodes every @expression. Only values wrapped in an IHtmlContent such as HtmlString (Html.Raw) are written untouched.
  3. 3. Which method handles POST /Products?handler=Clear on a Razor Page?

    Handler names follow On + HTTP method + handler name, optionally ending in Async. A handler=Clear value on a POST selects OnPostClear (or OnPostClearAsync).
  4. 4. When would you pick a view component over a partial view?

    A view component is a class with InvokeAsync and its own view, and it can use dependency injection to load data. A partial view only renders the model it is given.

Summary

  • Razor mixes HTML with C#: @expression, @{ } blocks, @if/@foreach, @@ for a literal at sign.
  • A .cshtml file is compiled into a C# class; every @expression is HTML-encoded unless it is an IHtmlContent.
  • Layouts hold the shared frame (RenderBody, sections); _ViewStart and _ViewImports remove repetition; partials are reusable fragments.
  • Tag helpers (asp-for, asp-action, asp-page-handler) generate links and form fields from routing and your model.
  • View components are small controller-plus-view units with dependency injection.
  • Razor Pages pair a template with handlers named On + method + name; @page gives the file a route.
  • The runnable examples here are stand-ins; the real compiler needs a full project.

Next: Blazor Overview