SkillPilotAI

MVC and Razor

ASP.NET Core MVC splits a server-rendered web app into Models, Views and Controllers, and Razor is the view syntax that mixes C# with HTML. Razor HTML-encodes output by default, and layouts, partials, view components and tag helpers remove repetition.

64.1 Why is it used?

  • The demo builds HTML as a string in a Minimal API and puts q straight into it.
  • A script in q comes back in the response and the browser runs it: XSS.
  • String HTML has no automatic encoding, repeats the header on every page and mixes C# with HTML.
  • Fix: a view engine, which in ASP.NET Core is MVC with Razor.
C#
var builder = WebApplication.CreateBuilder(args);var app = builder.Build(); app.MapGet("/search", (string q) =>    Results.Content($"""        <html><body>        <h1>Shop</h1>        <p>Results for: {q}</p>        </body></html>        """, "text/html")); app.Run();
Output
$ curl -i -G localhost:5064/search \  --data-urlencode "q=<script>alert(1)</script>"HTTP/1.1 200 OKContent-Type: text/html<html><body><h1>Shop</h1><p>Results for: <script>alert(1)</script></p></body></html>

64.2 Setup: dotnet new mvc

  • The template comes with controllers, views and a layout.
  • AddControllersWithViews also registers the Razor view engine.
  • MapControllerRoute creates the default route: controller, then action, then optional id.
C#
var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllersWithViews();builder.Services.AddSingleton<ProductStore>();builder.Services.AddSingleton<CartStore>(); var app = builder.Build();app.MapStaticAssets(); app.MapControllerRoute(    name: "default",    pattern:      "{controller=Home}/{action=Index}/{id?}")    .WithStaticAssets(); app.Run();
Output
$ dotnet new mvc -n ShopThe template "ASP.NET Core Web App (Model-View-Controller)"was created successfully.Restore succeeded. $ dotnet run --urls http://localhost:5064info: Microsoft.Hosting.Lifetime[14]      Now listening on: http://localhost:5064info: Microsoft.Hosting.Lifetime[0]      Application started. Press Ctrl+C to shut down.

64.3 How it works

The MVC request flow
  1. 1.GET /Products/Details/2

  2. 2.Routing: {controller=Home}/{action=Index}/{id?} picks ProductsController.Details(2)

  3. 3.Action gets the product from the store (the Model)

  4. 4.return View(model): Views/Products/Details.cshtml is picked by convention

  5. 5.Razor renders the view inside _Layout (RenderBody), HTML-encoding every @value

  6. 6.HTML response goes to the browser

Model = data, View = Razor template, Controller = glue

64.4 Controller: data + View()

  • Inherit Controller (not ControllerBase), because view support lives there.
  • Index takes q from the query string and keeps it in ViewData.
  • View(products) passes the model; by convention Views/Products/Index.cshtml is rendered.
C#
using Microsoft.AspNetCore.Mvc; public class ProductsController(    ProductStore store,    CartStore cart) : Controller{    public IActionResult Index(string? q)    {        ViewData["Query"] = q;        var products = store.Search(q);        return View(products);    }}
Output
$ curl -i localhost:5064/ProductsHTTP/1.1 200 OKContent-Type: text/html; charset=utf-8<!DOCTYPE html><html lang="en"><head>    <title>Products - Shop</title>

64.5 Razor syntax

  • @model List<Product> makes Model strongly typed in the whole view.
  • The @ sign switches to C#: @Model.Count, @if, @foreach.
  • Every @value is HTML-encoded, so the same script search is printed as harmless text.
  • Html.Raw turns encoding off: use it only for trusted HTML.
HTML
@model List<Product>@{    ViewData["Title"] = "Products";} <h1>Products (@Model.Count)</h1>@if (TempData["Message"] is string msg){    <p class="alert">@msg</p>}<p>Results for: @ViewData["Query"]</p>@foreach (var p in Model){    <partial name="_ProductCard" model="p" />}
Output
$ curl localhost:5064/Products<h1>Products (3)</h1><p>Results for: </p><div class="card">    <h3>Mixer Grinder</h3>    <p>₹2499</p> $ curl -G localhost:5064/Products \  --data-urlencode "q=<script>alert(1)</script>"<h1>Products (0)</h1><p>Results for: &lt;script&gt;alert(1)&lt;/script&gt;</p>

64.6 Layout, partial views and view components

  • _ViewStart sets _Layout for every view; @RenderBody() is where the view's HTML goes.
  • The title comes from ViewData["Title"] set in the view ("Steel Bottle - Shop").
  • A partial view (name starts with _) is a reusable piece; <partial name="_ProductCard" model="p" /> renders one card per product.
  • A view component is a mini controller: CartSummaryViewComponent takes CartStore from DI and fetches its own count; <vc:cart-summary> renders it.
  • Partial = shows the model it gets; view component = fetches its own data.
HTML
<!DOCTYPE html><html lang="en"><head>    <title>@ViewData["Title"] - Shop</title>    <link rel="stylesheet" href="~/css/site.css" /></head><body>    <header>        <a asp-controller="Products"           asp-action="Index">Shop</a>        <vc:cart-summary></vc:cart-summary>    </header>    <main>@RenderBody()</main></body></html>
HTML
@model Product <div class="card">    <h3>@Model.Name</h3>    <p>₹@Model.Price</p>    <a asp-action="Details"       asp-route-id="@Model.Id">View</a></div>
Output
Shop    Cart (0)# Products (3)Mixer Grinder · ₹2499 · ViewSteel Bottle · ₹399 · ViewPressure Cooker · ₹1899 · View
C#
using Microsoft.AspNetCore.Mvc; public class CartSummaryViewComponent(    CartStore cart) : ViewComponent{    public IViewComponentResult Invoke()    {        var count = cart.Count;        return View(count);    }}
PieceWhat it isGets data fromUse for
Layout (_Layout.cshtml)Page shell with @RenderBody()ViewData (title)Header/footer written once
Partial view (_ProductCard)Reusable markup pieceThe model passed to itRepeated markup (product card)
View componentMini controller + viewIts own DI services (Invoke)UI with its own data (cart count in header)
Tag helperServer-side HTML attributes (asp-*)RoutingCorrect URLs and form fields

64.7 Tag helpers

  • asp-action, asp-route-id, asp-controller look like HTML attributes but build URLs from routing on the server.
  • @addTagHelper in _ViewImports turns them on.
  • If a route changes, the links update by themselves (no hardcoded URLs).
Output
$ curl -s localhost:5064/Products | grep href    <link rel="stylesheet" href="/css/site.css" />        <a href="/Products">Shop</a>    <a href="/Products/Details/1">View</a>    <a href="/Products/Details/2">View</a>    <a href="/Products/Details/3">View</a>

64.8 TempData across a redirect

  • AddToCart is [HttpPost]; it updates the cart, sets TempData["Message"] and redirects to Index.
  • The response is 302 and the message is stored in a cookie.
  • The next request shows the message; after a refresh it is gone.
  • Checkpoint: with ViewData instead, the message never shows, because ViewData lives for one request and the redirect starts a new one.
C#
[HttpPost]public IActionResult AddToCart(int id){    var product = store.Find(id);    if (product is null) return NotFound();     cart.Add();    TempData["Message"] =        $"{product.Name} added to cart";    return RedirectToAction(nameof(Index));}
Output
$ curl -i -c jar.txt -X POST \  localhost:5064/Products/AddToCart/1HTTP/1.1 302 FoundLocation: /ProductsSet-Cookie: .AspNetCore.Mvc.CookieTempDataProvider=CfDJ8GLx…;  path=/; samesite=lax; httponly $ curl -b jar.txt -c jar.txt localhost:5064/Products<span class="cart">Cart (1)</span><h1>Products (3)</h1>    <p class="alert">Mixer Grinder added to cart</p><p>Results for: </p> $ curl -b jar.txt -c jar.txt localhost:5064/Products<span class="cart">Cart (1)</span><h1>Products (3)</h1><p>Results for: </p>
TempData across a redirect
  1. 1.POST /Products/AddToCart/1: cart updated

  2. 2.TempData["Message"] set, stored in a cookie

  3. 3.302 Found, Location: /Products

  4. 4.Browser GETs /Products: message read and shown

  5. 5.Refresh: message is gone (TempData is deleted once read)

Output
# same action, but ViewData["Message"] instead of TempData$ curl -i -c jar.txt -X POST \  localhost:5064/Products/AddToCart/1HTTP/1.1 302 FoundLocation: /Products$ curl -b jar.txt -L localhost:5064/Products<span class="cart">Cart (1)</span><h1>Products (3)</h1><p>Results for: </p>

64.9 Comparison: @model vs ViewData vs ViewBag vs TempData

StoreLifetimeTyped?Use for
@modelCurrent requestYesMain page data
ViewData["Key"]Current requestNo (object)Small extras like the title, query
ViewBag.KeyCurrent requestNo (dynamic)Same as ViewData; typos fail at runtime
TempData["Key"]Until read (survives a redirect)NoMessage after a redirect

64.10 Common mistakes

  • Building HTML by string concatenation: no encoding, XSS.
  • Main page data through ViewBag: a typo (ViewBag.Prodcts) builds fine and gives a 500 at runtime.
  • Html.Raw on user input: turns off the XSS protection.
  • Using ViewData for a message after a redirect: it is lost.
  • Hardcoding URLs instead of tag helpers.
  • Believing MVC is outdated: it is fully supported in .NET 10. Razor (view syntax) is not the same as Razor Pages.
HTML
// Wrong: dynamic ViewBag, typo caught at runtime// ControllerViewBag.Products = store.Search(q);// View@foreach (var p in ViewBag.Prodcts){    <li>@p.Name</li>}// GET /Legacy: 500// NullReferenceException // Right: typed model, typo caught at build time// Controllerreturn View(store.Search(q));// View@model List<Product>@foreach (var p in Model){    <li>@p.Name</li>}// typo p.Nmae: build error CS1061

64.11 Interview tips

  • Flow: routing picks controller + action, the action builds the model and returns View, Razor renders HTML with the layout.
  • Razor HTML-encodes output automatically, which protects against XSS.
  • Partial views reuse markup, view components fetch their own data.
  • ViewData lasts one request, TempData survives a redirect.
  • Razor is the syntax used by MVC, Razor Pages and Blazor.