MVC controllers and views
MVC controllers and views
MVC separates request coordination (controller), the data passed to the template (model), and HTML presentation (view). A controller action returns a result, not necessarily a JSON response. A Razor view is a server-side .cshtml template; its rendered HTML is sent to the browser. Razor components are a different UI model. Keep business decisions out of templates and pass only the fields needed for display.
Register controllers and views with AddControllersWithViews; MapControllers maps attribute routes, while MapControllerRoute establishes conventional routes. A controller named CatalogController returning View(model) from Index normally resolves Views/Catalog/Index.cshtml, then shared locations. @model declares the expected model type. Razor encodes ordinary string expressions for HTML contexts; never bypass encoding for untrusted text with Html.Raw. Keep stored values unencoded and encode at the rendering boundary. HTML text encoding alone does not validate URL schemes or safely embed data in JavaScript. Prefer framework binding and serialization for those separate contexts. Layouts provide document structure with RenderBody; partials render small reusable markup, while view components can encapsulate more substantial rendering logic. _ViewStart can choose layouts, and _ViewImports brings namespaces and tag helpers into scope. These conventions can be customized.
Baseline: .NET 10 / C# 14. Examples are independent Web SDK projects, with source files shown below or in the companion fixture. All expected outputs are reasoned, not executed. Run only in an isolated environment with an approved SDK, no real data, no launch profile and no external network. The finite loopback host uses ephemeral data protection keys and a test-only cookie container. No production security configuration is implied.
Render a typed book card
The controller supplies a small view model. Check that the title is rendered as text, not unescaped markup.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});builder.Services.AddControllersWithViews();await using var app = builder.Build();app.MapControllers();using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var response = await client.GetAsync("/catalog", deadline.Token); var body = await response.Content.ReadAsStringAsync(deadline.Token); Check(response.IsSuccessStatusCode && body.Contains("Map & Atlas") && body.Contains("120"), "encoded catalog"); Console.WriteLine("encoded catalog");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}public sealed record BookCard(string Title, int Pages);public sealed class CatalogController : Controller{ [HttpGet("/catalog")] public IActionResult Index() => View(new BookCard("Map & Atlas", 120));}Companion source files (place under the project root exactly as named):
Views/Catalog/Index.cshtml
@model BookCard<h1>@Model.Title</h1><p>Pages: @Model.Pages</p>Expected console observation (unexecuted):
encoded catalogThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Reuse a layout and partial
A layout wraps the entire page; a partial renders a specific fragment. Both use server-side Razor.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});builder.Services.AddControllersWithViews();await using var app = builder.Build();app.MapControllers();using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var response = await client.GetAsync("/catalog", deadline.Token); var body = await response.Content.ReadAsStringAsync(deadline.Token); Check(response.IsSuccessStatusCode && body.Contains("<main>") && body.Contains("Pages: 120"), "layout and partial"); Console.WriteLine("layout and partial");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}public sealed record BookCard(string Title, int Pages);public sealed class CatalogController : Controller{ [HttpGet("/catalog")] public IActionResult Index() => View(new BookCard("Map & Atlas", 120));}Companion source files (place under the project root exactly as named):
Views/_ViewImports.cshtml
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpersViews/_ViewStart.cshtml
@{ Layout = "_Layout"; }Views/Shared/_Layout.cshtml
<!doctype html><html lang="en"><head><title>Catalog</title></head><body><main>@RenderBody()</main></body></html>Views/Catalog/Index.cshtml
@model BookCard<h1>@Model.Title</h1><partial name="_Book" model="Model" />Views/Catalog/_Book.cshtml
@model BookCard<p>Pages: @Model.Pages</p>Expected console observation (unexecuted):
layout and partialThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Choose view or not-found result
A route value selects a known item; missing data is not a blank successful page.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});builder.Services.AddControllersWithViews();await using var app = builder.Build();app.MapControllers();using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var found = await client.GetAsync("/books/4", deadline.Token); using var missing = await client.GetAsync("/books/5", deadline.Token); Check(found.IsSuccessStatusCode && (await found.Content.ReadAsStringAsync(deadline.Token)).Contains("Field Guide"), "book view"); Check(missing.StatusCode == HttpStatusCode.NotFound, "missing book"); Console.WriteLine("200 / 404");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}public sealed class BooksController : Controller{ [HttpGet("/books/{id:int}")] public IActionResult Details(int id) => id == 4 ? View(model: "Field Guide") : NotFound();}Companion source files (place under the project root exactly as named):
Views/Books/Details.cshtml
@model string<h1>@Model</h1>Expected console observation (unexecuted):
200 / 404The assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Common mistakes and limitations
Do not pass persistence entities with unnecessary private fields to views. Do not construct view paths from request input. HTML encoding is context-specific: it does not validate URL destinations or make arbitrary script contexts safe.
Practice and recap
Add a second known book and a shared partial showing only title and page count. Test the known and unknown IDs; explain why the controller decides the status and the view does not.
Use the fixture assertions to verify the behavior after modification. Explain the observed result before moving to the next lesson.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
MVC controllers and views — knowledge check
Apply the lesson concepts to the following scenarios.
Which layer chooses NotFound for a missing book?
What does @model BookCard declare?
Why is Map & Atlas encoded in a view?
Where does RenderBody place content?
What is a useful role for a partial?