9.1 โ The MVC Pattern in ASP.NET Core¶
โ Roadmap ยท Section: 9. MVC, Razor Pages and Views Prev: 8.10 Catch-all routes and slugs ยท Next: 9.2 Controllers
Markers: ๐ฅ ๐ฏ ยท Confidence: ๐ด ยท Last reviewed: โ
TL;DR¶
MVC splits a web request into three responsibilities: the Model holds the data and rules, the View renders the output, and the Controller coordinates between them.
- The point is separation of concerns โ you can change how something looks without touching how it works.
- In ASP.NET Core, MVC is one framework that also powers Web APIs, where there is no View at all.
- โ ๏ธ The most common mistake is a fat controller โ business logic in the controller instead of the model or a service.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| MVC | an architectural pattern | Model-View-Controller. Splits presentation from logic from data. |
| Model | the data and rules | Your domain objects and business logic. Knows nothing about HTTP. |
| View | a template | A .cshtml file that renders HTML. Knows nothing about the database. |
| Controller | a class | Receives the request, calls a service, chooses a result. The coordinator. |
| Action | a public method on a controller | Handles one request. Returns an IActionResult or a value. |
| ViewModel | a class shaped for one view | What the view actually needs, distinct from your domain entity. See 9.8. |
| Separation of concerns | a design principle | Each part has one reason to change. |
| Fat controller | an anti-pattern | Business logic in the controller, making it untestable and unreusable. |
AddControllersWithViews |
a method | Registers MVC with view support. |
AddControllers |
a method | Registers MVC without views โ for APIs. |
| Razor Pages | an alternative | Page-focused rather than controller-focused. See 9.7. |
The concept¶
The three parts¶
Model โ the data and the rules that govern it. An Order class, the logic that decides
whether it can be cancelled, the repository that loads it. It knows nothing about the web.
View โ a template that turns data into HTML. It knows nothing about where the data came from.
Controller โ the coordinator. It receives the request, asks a service for what it needs, and decides what to return.
flowchart LR
R["Request"] --> C["Controller<br/>coordinates"]
C --> M["Model / Service<br/>does the work"]
M --> C
C --> V["View<br/>renders"]
V --> Resp["HTML response"]
A picture: a restaurant. The waiter (controller) takes your order and carries it between you and the kitchen โ they do not cook. The kitchen (model) prepares the food and knows nothing about which table it goes to. The plate (view) presents it. Change the plating without changing the recipe; change the recipe without retraining the waiter.
What the separation actually buys you¶
The abstract answer is "separation of concerns", which is true and unhelpful. The concrete benefits:
You can test the logic without the web. If order-cancellation rules live in a service, a unit
test constructs it with fakes and runs in milliseconds
(6.12). If they live in a controller, the
test needs an HttpContext.
You can reuse the logic. The same service serves a controller, a background job and a gRPC endpoint. Logic inside a controller action serves exactly one URL.
You can change presentation independently. Swapping an HTML view for a JSON response should not touch the business rules โ and in ASP.NET Core that is literally the difference between an MVC app and an API.
โ ๏ธ The mistake everyone makes¶
// โ A fat controller โ logic that does not belong here
[HttpPost("{id:guid}/cancel")]
public async Task<IActionResult> Cancel(Guid id, CancellationToken ct)
{
var order = await _db.Orders.Include(o => o.Lines)
.FirstOrDefaultAsync(o => o.Id == id, ct);
if (order is null) return NotFound();
if (order.Status == OrderStatus.Shipped)
return BadRequest("Cannot cancel a shipped order");
if (order.CreatedAt < DateTimeOffset.UtcNow.AddDays(-30))
return BadRequest("Orders older than 30 days cannot be cancelled");
order.Status = OrderStatus.Cancelled;
order.CancelledAt = DateTimeOffset.UtcNow;
foreach (var line in order.Lines)
await _inventory.ReturnStockAsync(line.ProductId, line.Quantity, ct);
await _db.SaveChangesAsync(ct);
await _email.SendAsync(order.CustomerEmail, "Order cancelled", "...", ct);
return NoContent();
}
Every business rule about cancellation lives in an HTTP handler. To test "can a 40-day-old order
be cancelled?", you have to construct a controller and an HttpContext. To cancel an order from a
background job, you copy the logic.
// โ Thin controller โ translate, delegate, translate back
[HttpPost("{id:guid}/cancel")]
public async Task<IActionResult> Cancel(Guid id, CancellationToken ct)
{
var result = await _orders.CancelAsync(id, ct);
return result.Status switch
{
CancelStatus.Success => NoContent(),
CancelStatus.NotFound => NotFound(),
_ => BadRequest(result.Reason)
};
}
The controller's job is translation โ HTTP in, HTTP out. Everything between belongs elsewhere.
How it works¶
The simple version โ the request flow¶
flowchart TD
A["Request: GET /orders/42"] --> B["Routing<br/>selects OrdersController.Details"]
B --> C["Model binding<br/>URL โ id parameter"]
C --> D["Filters<br/>authorization, validation"]
D --> E["Action executes<br/>calls a service"]
E --> F["Returns an IActionResult"]
F --> G["Result executes<br/>renders the view or serialises JSON"]
G --> H["Response"]
Two things worth noticing.
The action does not write the response. It returns a description of what should happen โ
View(model) or Ok(dto) โ and the framework executes that afterwards. That is what makes
actions testable: you assert on the returned result object without any HTTP involved
(9.3).
Filters run around the action, inside the endpoint. They are MVC's extension point, distinct from middleware (5.13).
Registering it¶
// Full MVC โ controllers plus views
builder.Services.AddControllersWithViews();
// API only โ no view engine, no Razor
builder.Services.AddControllers();
// Razor Pages โ see 9.7
builder.Services.AddRazorPages();
โ ๏ธ AddControllers versus AddControllersWithViews matters. For an API, the first avoids
registering the entire Razor view engine โ less startup work and a smaller surface. Calling
View(...) from a controller registered with AddControllers throws at runtime because there is
no view engine to find the template.
โ ๏ธ MVC is also how Web APIs work¶
This confuses people coming from other frameworks: an ASP.NET Core Web API is MVC with the V left out.
// Same framework, same controller base, same filters, same model binding
[ApiController]
public class OrdersController : ControllerBase
{
[HttpGet("{id:guid}")]
public async Task<ActionResult<OrderDto>> Get(Guid id) { }
}
Routing, model binding, filters and action results are all shared. The only difference is that instead of returning a rendered view, the result is serialised to JSON by a formatter (10.5).
So learning MVC's mechanics is not wasted effort on an API project โ it is the API's mechanics.
The deeper detail โ where the "M" actually lives¶
โ ๏ธ "Model" is the vaguest of the three letters, and the confusion is real.
In practice a modern ASP.NET Core application has several things people call a model:
| Thing | Purpose |
|---|---|
| Domain entity | Order โ the business object, with rules |
| EF entity | Often the same class, mapped to a table (13.4) |
| ViewModel | Shaped for one view โ what the page needs (9.8) |
| DTO | Shaped for the API contract (10.11) |
| Request model | What model binding populates from the request |
Classic MVC assumed one "Model". Real applications separate them, because a class shaped for the database is rarely shaped for a web page or an API response.
โ ๏ธ Passing an EF entity straight to a view or an API response is the common shortcut, and it causes three problems: it leaks your schema, it enables over-posting (11.10), and lazy-loaded navigation properties can trigger queries during serialization (13.8).
MVC versus the alternatives¶
| Suits | |
|---|---|
| MVC | Server-rendered sites with several actions per resource; Web APIs |
| Razor Pages | Server-rendered pages where each URL is one page (9.7) |
| Minimal APIs | Small services, AOT, fewer ceremony layers (10.12) |
| Blazor | Interactive UI in C# (9.9) |
They coexist. One application can serve Razor Pages for the site, MVC controllers for admin, and minimal APIs for its JSON endpoints โ all sharing the same host, DI and middleware.
Code¶
A properly layered slice:
// โโ MODEL: the domain object owns its own rules โโ
public class Order
{
public Guid Id { get; init; }
public OrderStatus Status { get; private set; }
public DateTimeOffset CreatedAt { get; init; }
public List<OrderLine> Lines { get; init; } = [];
// The rule lives WITH the data it governs โ see 22.14 on anemic models
public bool CanBeCancelled(DateTimeOffset now) =>
Status is OrderStatus.Pending or OrderStatus.Confirmed &&
CreatedAt > now.AddDays(-30);
public void Cancel(DateTimeOffset now)
{
if (!CanBeCancelled(now))
throw new InvalidOperationException("This order cannot be cancelled.");
Status = OrderStatus.Cancelled;
}
}
// โโ SERVICE: orchestrates, but still knows nothing about HTTP โโ
public class OrderService(
IOrderRepository repo,
IInventoryService inventory,
TimeProvider time) : IOrderService
{
public async Task<CancelResult> CancelAsync(Guid id, CancellationToken ct)
{
var order = await repo.GetAsync(id, ct);
if (order is null) return CancelResult.NotFound();
if (!order.CanBeCancelled(time.GetUtcNow()))
return CancelResult.Rejected("This order can no longer be cancelled.");
order.Cancel(time.GetUtcNow());
await repo.SaveAsync(order, ct);
foreach (var line in order.Lines)
await inventory.ReturnStockAsync(line.ProductId, line.Quantity, ct);
return CancelResult.Success();
}
}
// โโ CONTROLLER: translation only โโ
[Route("orders")]
public class OrdersController(IOrderService orders) : Controller
{
[HttpGet("{id:guid}")]
public async Task<IActionResult> Details(Guid id, CancellationToken ct)
{
var order = await orders.GetAsync(id, ct);
if (order is null) return NotFound();
// Map to a ViewModel โ the view gets what it needs, not the entity
return View(OrderDetailsViewModel.From(order));
}
[HttpPost("{id:guid}/cancel")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Cancel(Guid id, CancellationToken ct)
{
var result = await orders.CancelAsync(id, ct);
if (result.IsNotFound) return NotFound();
if (!result.IsSuccess)
{
TempData["Error"] = result.Reason; // see 9.6
return RedirectToAction(nameof(Details), new { id });
}
return RedirectToAction(nameof(Details), new { id });
}
}
@* โโ VIEW: rendering only โโ *@
@model OrderDetailsViewModel
<h1>Order @Model.Reference</h1>
<p>Placed @Model.CreatedAt.ToString("d MMMM yyyy")</p>
@if (Model.CanCancel)
{
<form asp-action="Cancel" asp-route-id="@Model.Id" method="post">
<button type="submit">Cancel this order</button>
</form>
}
Notice Model.CanCancel is a property on the ViewModel, not a rule evaluated in the view. The
view asks a question; it does not decide the answer. That is the line that keeps views simple and
logic testable.
Interview questions¶
Q: Explain the MVC pattern.
It splits a request into three responsibilities. The Model holds the data and the business rules and knows nothing about HTTP. The View is a template that renders output and knows nothing about where the data came from. The Controller coordinates โ it receives the request, calls a service, and returns a result describing what should happen. The value is that each part has one reason to change: you can alter how something is presented without touching the rules, and test the rules without standing up the web stack.
Q: What is the most common mistake with MVC?
Fat controllers โ putting business logic in the action instead of in the model or a service. It
feels natural because the controller is where the request arrives, but it makes the logic
untestable without an HttpContext and unusable from anywhere else, so the same rules get copied
into a background job. The controller's job is translation: turn an HTTP request into a service
call, and turn the result back into an HTTP response. Everything between belongs elsewhere.
Q: How does MVC relate to Web APIs in ASP.NET Core?
A Web API is MVC without the View. It is the same framework โ the same routing, model binding,
filters, controller base and action results. The only difference is that instead of rendering a
Razor template, the result is serialised by an output formatter, usually to JSON. That is why
AddControllers and AddControllersWithViews differ only in whether the view engine is
registered. So understanding MVC's mechanics is not wasted on an API project; it is the API's
mechanics.
Q: What does "Model" actually mean in a modern application?
It is the vaguest of the three letters, because classic MVC assumed one model and real applications have several. There is the domain entity with its rules, often also the EF entity mapped to a table, a ViewModel shaped for a particular page, and a DTO shaped for the API contract. Keeping them separate matters โ passing an EF entity straight to a view or an API response leaks your schema, enables over-posting, and can trigger lazy-loading queries during serialization.
Traps โ ๏ธ¶
- Business logic in controllers makes it untestable and unreusable. Push it into services or the domain.
- Passing EF entities to views or API responses leaks the schema and enables over-posting.
AddControllershas no view engine. CallingView(...)then throws at runtime.- Logic in views โ
@if (order.Status == ... && order.CreatedAt > ...)โ is untestable. Put it on the ViewModel. - "Model" is ambiguous. Be specific about which one you mean.
- The action does not write the response, it returns a description of one. That is what makes it testable.
- An anemic model โ entities with only properties, all logic in services โ is a recognised anti-pattern (22.14).
Related¶
- 9.2 Controllers โ
ControllerversusControllerBase - 9.3 Action results โ what an action returns
- 9.8 ViewModels โ keeping entities out of views
- 9.7 Razor Pages โ the page-focused alternative
- 5.13 Middleware vs filters โ where filters sit
- 10.11 DTOs โ the API equivalent of a ViewModel
- 22.14 Anti-patterns โ fat controllers and anemic models
- 6.12 DI and testability โ why thin controllers test better