MVC Pattern
Models, Views, Controllers and separation of concerns.
MVC Pattern in ASP.NET Core
Category: ASP.NET Core Fundamentals
Difficulty: Intermediate
Target framework: .NET 9+
Previous topic: Logging abstractions
Next topic: Razor Pages
1. About
Understand Models, Views, Controllers, request flow, and production implementation in ASP.NET Core.
Prerequisites
- Basic C# and object-oriented programming
- HTTP request and response fundamentals
- Basic routing and dependency injection
- Familiarity with logging abstractions
Learning outcomes
By the end of this module, you will be able to:
- Explain the Model–View–Controller pattern and its responsibilities.
- Trace an HTTP request through ASP.NET Core MVC.
- Build controllers, models, ViewModels, and Razor views.
- Use model binding, validation, dependency injection, and service classes.
- Apply production-minded security, performance, and testing practices.
- Compare MVC with Razor Pages, Minimal APIs, and Web API controllers.
2. Introduction
What is MVC?
MVC stands for Model–View–Controller. It is an architectural pattern that separates an application's data and business rules, user interface, and request-handling responsibilities.
- Model: Represents application data and, depending on its role, business rules.
- View: Presents information to the user. In ASP.NET Core MVC, views commonly use Razor
.cshtmlfiles. - Controller: Receives a request, coordinates the work, and chooses the response.
MVC exists to avoid placing database access, business decisions, request handling, and HTML generation in one large component. Separating these responsibilities makes code easier to understand, test, change, and maintain.
| Problem | How MVC helps |
|---|---|
| HTML and business logic are tangled | Views focus on presentation while services/domain components own business rules |
| Controllers become hard to understand | Actions can coordinate focused services |
| UI changes affect database logic | ViewModels separate UI needs from persistence models |
| Testing is difficult | Services and controller behavior can be tested independently |
| Teams need a consistent structure | MVC provides familiar conventions and responsibilities |
Important: MVC is not merely three folders named
Models,Views, andControllers. A project can have those folders and still be poorly separated. The pattern is about responsibilities, not folder names.
3. Real-life analogy: A restaurant
Imagine a customer ordering a meal.
| Restaurant concept | MVC equivalent | Responsibility |
|---|---|---|
| Ingredients and recipe rules | Model/domain concepts | Represent the data and rules involved |
| Waiter coordinating the order | Controller | Receive the request and coordinate the work |
| Menu/order presentation | View | Present information clearly to the customer |
The waiter does not grow the ingredients or design the menu. The waiter receives the request and coordinates the process. Similarly, a controller should not become the place where every business rule, SQL query, and HTML concern lives.
The analogy is not exact: a real MVC Model is not necessarily a database entity, and the View is a template rendered by the server rather than a physical menu.
4. Architecture diagram
This is a common server-rendered flow, not a requirement for every action. An action may return a redirect, JSON, a file, or a status code without rendering a Razor view.
5. Concept explanation
5.1 Models
A Model represents application information and may represent domain rules. It does not have to be a database table or EF Core entity.
Common model roles include:
| Type | Purpose | Example |
|---|---|---|
| Domain model | Represents a business concept and its rules | Order, Product |
| Persistence entity | Represents stored data | ProductEntity |
| ViewModel | Supplies the data a particular view needs | ProductDetailsViewModel |
| Input model | Defines accepted user input | CreateProductViewModel |
| DTO | Transfers data across a boundary | ProductDto |
These roles can overlap in a small application, but keeping them distinct becomes useful as complexity grows.
namespace MvcDemo.Models;
public sealed class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public int StockQuantity { get; set; }
}
A UI-specific model can expose only the fields the page needs:
namespace MvcDemo.Models;
public sealed class ProductDetailsViewModel
{
public int Id { get; init; }
public string Name { get; init; } = string.Empty;
public decimal Price { get; init; }
public bool IsAvailable { get; init; }
public string AvailabilityMessage =>
IsAvailable ? "In stock" : "Currently unavailable";
}
Why use a ViewModel? A database entity may contain internal fields that the UI should not expose. A ViewModel also lets a page combine data from several sources without forcing the UI to understand persistence details.
5.2 Views
A View displays data and gathers user input. ASP.NET Core MVC commonly uses Razor .cshtml files.
Views/Products/Details.cshtml:
@model MvcDemo.Models.ProductDetailsViewModel
<h1>@Model.Name</h1>
<p>Price: @Model.Price.ToString("C")</p>
<p>@Model.AvailabilityMessage</p>
@modeldeclares the model type expected by the view.@Modelaccesses the object supplied by the controller.- Razor combines HTML and C# expressions to generate the response.
Views should generally avoid database queries, payment calculations, authorization decisions, and complex business workflows. Keep presentation logic simple; move business rules into suitable services or domain components.
Razor automatically HTML-encodes ordinary string expressions in HTML contexts. Do not assume this protects every context: raw HTML, JavaScript, CSS, and URLs need context-appropriate handling.
5.3 Controllers and actions
A controller receives a matched request and coordinates the response.
using Microsoft.AspNetCore.Mvc;
using MvcDemo.Models;
namespace MvcDemo.Controllers;
public sealed class ProductsController : Controller
{
public IActionResult Details()
{
var product = new ProductDetailsViewModel
{
Id = 1,
Name = "Mechanical Keyboard",
Price = 2499m,
IsAvailable = true
};
return View(product);
}
}
An action method is a method MVC can invoke as an endpoint when routing and action-selection rules match it. IActionResult lets an action return different kinds of HTTP responses.
| Result | Typical use | Example |
|---|---|---|
View() | Render HTML | return View(model); |
RedirectToAction() | Redirect to another action | return RedirectToAction(nameof(Index)); |
NotFound() | HTTP 404 | return NotFound(); |
BadRequest() | HTTP 400 | return BadRequest(); |
Ok() | HTTP 200, often with data | return Ok(data); |
Json() | Return JSON | return Json(data); |
File() | Return a file | return File(bytes, contentType); |
StatusCode() | Return a specific status | return StatusCode(503); |
Use result types that accurately describe the response. An MVC controller can return HTML or data; MVC is not limited to server-rendered pages.
5.4 Routing
Routing maps an incoming URL and HTTP method to an endpoint.
A conventional route often looks like:
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
For /Products/Details/10, the conventional route typically selects ProductsController, action Details, and binds 10 to id.
Attribute routing puts route templates on controllers or actions:
[Route("products")]
public sealed class ProductsController : Controller
{
[HttpGet("{id:int}")]
public IActionResult Details(int id) => Content($"Product {id}");
}
The route template and HTTP method constraints help determine which endpoint is eligible.
5.5 Model binding
Model binding converts supported request data—such as route values, query-string values, and form fields—into action parameters or model properties.
[HttpGet("search")]
public IActionResult Search(string searchTerm)
{
return Content($"Search term: {searchTerm}");
}
A request such as /Products/Search?searchTerm=keyboard can bind keyboard to searchTerm when the route is configured accordingly.
For more complex actions, use a dedicated input model rather than accepting many unrelated primitive parameters.
5.6 Model validation
Validation checks whether bound input satisfies declared rules. Data annotations are a common starting point:
using System.ComponentModel.DataAnnotations;
namespace MvcDemo.Models;
public sealed class CreateProductViewModel
{
[Required]
[StringLength(100, MinimumLength = 2)]
public string Name { get; set; } = string.Empty;
[Range(typeof(decimal), "0.01", "1000000")]
public decimal Price { get; set; }
}
In a typical MVC form action, check ModelState.IsValid before processing the input. Validation attributes do not replace business-rule validation—for example, a price being positive does not establish that the current user is allowed to set that price.
5.7 Dependency injection
ASP.NET Core has built-in dependency injection (DI). Controllers can receive services through their constructors instead of creating concrete dependencies themselves.
public sealed class ProductsController : Controller
{
private readonly IProductService _products;
public ProductsController(IProductService products)
{
_products = products;
}
}
Register the implementation in Program.cs:
builder.Services.AddScoped<IProductService, ProductService>();
Constructor injection makes dependencies explicit and helps isolate tests. The appropriate service lifetime depends on the service's state and dependencies.
5.8 Middleware, filters, and MVC
Middleware runs in the HTTP pipeline and can process requests before and after endpoint execution. MVC filters run at particular stages of MVC action or result processing. They are related but not interchangeable.
- Use middleware for broad HTTP concerns such as exception handling and request logging.
- Use authorization policies and framework authorization mechanisms to protect resources.
- Use MVC filters for MVC-specific cross-cutting behavior where appropriate.
- Keep business decisions in application/domain components rather than hiding them in presentation infrastructure.
6. Important terminology
| Term | Meaning | Example |
|---|---|---|
| MVC | Model–View–Controller pattern | Separating a product page into responsibilities |
| Model | Application data and/or domain concepts | Product |
| View | UI template | Details.cshtml |
| Controller | Coordinates request handling | ProductsController |
| Action | Controller endpoint method | Details(int id) |
| Razor | Syntax for HTML templates with C# | @Model.Name |
| Routing | Maps requests to endpoints | /Products/Details/10 |
| Model binding | Converts request data into .NET values | Query string to searchTerm |
| ModelState | Stores binding and validation state/errors | ModelState.IsValid |
| ViewModel | Data shaped for a particular view | ProductDetailsViewModel |
| DI | Supplies dependencies to components | IProductService |
| Action result | Describes a response to produce | View(), NotFound() |
| Anti-forgery token | Helps defend form submissions against CSRF | @Html.AntiForgeryToken() |
7. How it works internally
A typical request follows these steps:
- The browser sends an HTTP request.
- ASP.NET Core middleware processes the request in pipeline order.
- Endpoint routing selects a matching endpoint based on the route and applicable constraints.
- MVC creates the controller through its activation mechanism and resolves its dependencies from DI.
- Model binding reads supported request values into action parameters and input models.
- Validation runs and records errors in
ModelState. - MVC invokes the selected action if the request is eligible for execution.
- The action calls application services and receives the result.
- The action returns a result—for example, a view, redirect, JSON response, or error status.
- For a view result, MVC locates the view, executes Razor, and produces HTML.
- The HTTP response travels back through the remaining middleware to the browser.
This is a conceptual flow. Actual framework internals include more stages, and an action that returns a redirect or JSON does not need to execute a Razor view.
8. Syntax explained
Controller declaration
public sealed class ProductsController : Controller
public: makes the type accessible.sealed: prevents other classes from inheriting from this controller; optional.ProductsController: follows the conventionalControllersuffix.: Controller: inherits MVC helper functionality, includingView()andNotFound().
Action signature
public IActionResult Details(int id)
IActionResult: represents a response result.Details: action name, subject to routing and action-selection configuration.int id: a parameter that MVC may bind from route data or another configured source.
Returning a view
return View(productViewModel);
The controller returns a view result and passes the object to the view. MVC normally searches the action-specific view path and then applicable shared view locations.
Attribute routing
[HttpGet("{id:int}")]
HttpGet: constrains the action to GET requests.{id:int}: route parameter with an integer constraint.
Route constraints help select routes; they are not a replacement for input validation or authorization.
9. Code examples
The examples progress from a minimal MVC action to a more production-minded implementation.
9.1 Simple example
Goal: Return a Razor view with a product model.
Models/ProductViewModel.cs:
namespace MvcDemo.Models;
public sealed class ProductViewModel
{
public string Name { get; init; } = string.Empty;
public decimal Price { get; init; }
}
Controllers/ProductsController.cs:
using Microsoft.AspNetCore.Mvc;
using MvcDemo.Models;
namespace MvcDemo.Controllers;
public sealed class ProductsController : Controller
{
[HttpGet]
public IActionResult Details()
{
var model = new ProductViewModel
{
Name = "Mechanical Keyboard",
Price = 2499m
};
return View(model);
}
}
Views/Products/Details.cshtml:
@model MvcDemo.Models.ProductViewModel
<h1>@Model.Name</h1>
<p>Price: @Model.Price.ToString("C")</p>
When the action is reached through a matching route, MVC passes the model to Razor and returns rendered HTML.
9.2 Intermediate example: Create a product with validation
Models/CreateProductViewModel.cs:
using System.ComponentModel.DataAnnotations;
namespace MvcDemo.Models;
public sealed class CreateProductViewModel
{
[Required]
[StringLength(100, MinimumLength = 2)]
public string Name { get; set; } = string.Empty;
[Range(typeof(decimal), "0.01", "1000000")]
public decimal Price { get; set; }
}
Controllers/ProductsController.cs:
using Microsoft.AspNetCore.Mvc;
using MvcDemo.Models;
namespace MvcDemo.Controllers;
public sealed class ProductsController : Controller
{
// In a real application, inject a service and persist through that service.
[HttpGet]
public IActionResult Create()
{
return View(new CreateProductViewModel());
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(CreateProductViewModel model)
{
if (!ModelState.IsValid)
{
// Return the same view so validation errors can be displayed.
return View(model);
}
// Demo only: a real app would call an application service to save the product.
TempData["Message"] = $"Product '{model.Name}' passed validation.";
// Post/Redirect/Get reduces accidental resubmission on refresh.
return RedirectToAction(nameof(Create));
}
}
Views/Products/Create.cshtml:
@model MvcDemo.Models.CreateProductViewModel
<h1>Create product</h1>
<form asp-action="Create" method="post">
<div asp-validation-summary="ModelOnly"></div>
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
<label asp-for="Price"></label>
<input asp-for="Price" />
<span asp-validation-for="Price"></span>
<button type="submit">Save</button>
</form>
@if (TempData["Message"] is string message)
{
<p>@message</p>
}
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
The form tag helper generates the form action and, for a typical POST form, an anti-forgery token when configured through the standard MVC form helpers. The controller explicitly validates the token.
Production note: This example intentionally does not persist anything. Replace the demo comment with a service call, enforce business rules there, and handle persistence errors. Client-side validation improves usability but does not replace server-side validation.
9.3 Production example: Controller + service + EF Core
A production-minded MVC application keeps the controller thin and moves use-case logic and data access out of the action.
Product entity
Data/ProductEntity.cs:
namespace MvcDemo.Data;
public sealed class ProductEntity
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}
DbContext
Data/AppDbContext.cs:
using Microsoft.EntityFrameworkCore;
namespace MvcDemo.Data;
public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
: DbContext(options)
{
public DbSet<ProductEntity> Products => Set<ProductEntity>();
}
ViewModel
Models/ProductListItemViewModel.cs:
namespace MvcDemo.Models;
public sealed class ProductListItemViewModel
{
public int Id { get; init; }
public string Name { get; init; } = string.Empty;
public decimal Price { get; init; }
}
Service contract and implementation
Services/IProductService.cs:
using MvcDemo.Models;
namespace MvcDemo.Services;
public interface IProductService
{
Task<IReadOnlyList<ProductListItemViewModel>> GetProductsAsync(
CancellationToken cancellationToken);
}
Services/ProductService.cs:
using Microsoft.EntityFrameworkCore;
using MvcDemo.Data;
using MvcDemo.Models;
namespace MvcDemo.Services;
public sealed class ProductService(AppDbContext db) : IProductService
{
public async Task<IReadOnlyList<ProductListItemViewModel>> GetProductsAsync(
CancellationToken cancellationToken)
{
// Project directly to the shape required by the page.
return await db.Products
.AsNoTracking()
.OrderBy(p => p.Name)
.Select(p => new ProductListItemViewModel
{
Id = p.Id,
Name = p.Name,
Price = p.Price
})
.ToListAsync(cancellationToken);
}
}
Controller
Controllers/ProductsController.cs:
using Microsoft.AspNetCore.Mvc;
using MvcDemo.Services;
namespace MvcDemo.Controllers;
public sealed class ProductsController(IProductService products) : Controller
{
[HttpGet]
public async Task<IActionResult> Index(CancellationToken cancellationToken)
{
var model = await products.GetProductsAsync(cancellationToken);
return View(model);
}
}
View
Views/Products/Index.cshtml:
@model IReadOnlyList<MvcDemo.Models.ProductListItemViewModel>
<h1>Products</h1>
@if (Model.Count == 0)
{
<p>No products are available.</p>
}
else
{
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@foreach (var product in Model)
{
<tr>
<td>@product.Name</td>
<td>@product.Price.ToString("C")</td>
</tr>
}
</tbody>
</table>
}
Program.cs
using Microsoft.EntityFrameworkCore;
using MvcDemo.Data;
using MvcDemo.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IProductService, ProductService>();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Configure a DefaultConnection connection string using user secrets or a secure deployment configuration. Do not commit production credentials to source control. Add and apply EF Core migrations as part of the database setup process.
Why this design is better:
- The controller coordinates the request rather than writing SQL.
- The service contains the retrieval use case.
- EF Core performs asynchronous database I/O.
AsNoTracking()is appropriate for this read-only query.- Projection returns only the fields needed by the page.
- A cancellation token can propagate request cancellation to the query.
The example is a foundation, not a complete enterprise architecture. Larger applications may add domain models, authorization policies, pagination, caching, and more explicit error handling.
10. Recommended folder structure
A small-to-medium MVC application might use:
MvcDemo/
├── Controllers/
│ ├── HomeController.cs
│ └── ProductsController.cs
├── Data/
│ ├── AppDbContext.cs
│ └── ProductEntity.cs
├── Models/
│ ├── CreateProductViewModel.cs
│ ├── ProductDetailsViewModel.cs
│ └── ProductListItemViewModel.cs
├── Services/
│ ├── IProductService.cs
│ └── ProductService.cs
├── Views/
│ ├── Home/
│ │ └── Index.cshtml
│ ├── Products/
│ │ ├── Create.cshtml
│ │ ├── Details.cshtml
│ │ └── Index.cshtml
│ ├── Shared/
│ │ ├── _Layout.cshtml
│ │ └── _ValidationScriptsPartial.cshtml
│ ├── _ViewImports.cshtml
│ └── _ViewStart.cshtml
├── wwwroot/
│ ├── css/
│ └── js/
├── appsettings.json
└── Program.cs
For larger systems, organize by feature or application layer when that improves discoverability. Do not create extra abstractions or folders without a concrete need.
11. Execution flow: line by line
For the production Index action:
[HttpGet]
public async Task<IActionResult> Index(CancellationToken cancellationToken)
{
var model = await products.GetProductsAsync(cancellationToken);
return View(model);
}
[HttpGet]restricts this action to GET requests.- MVC matches the request to the controller and action through routing.
- MVC supplies the request cancellation token.
- The controller calls the injected
IProductService. awaitasynchronously waits for the service operation without blocking the request thread while the database I/O is pending.- The service queries EF Core and projects database rows to ViewModel objects.
- The returned collection is assigned to
model. View(model)creates a view result with that model.- MVC locates
Views/Products/Index.cshtml. - Razor renders the HTML and MVC sends it to the browser.
The action does not itself open a database connection or generate the HTML. Those responsibilities belong to other components in the flow.
12. Real project usage
MVC is useful for server-rendered web applications where a request typically produces an HTML page.
| Industry | Example | MVC responsibilities |
|---|---|---|
| E-commerce | Product catalog and order history | Controller coordinates catalog retrieval; View displays products; services enforce purchase rules |
| Banking | Account summary and transaction history | Controllers coordinate requests; authorization and services protect sensitive operations |
| Healthcare | Appointment management | Input models validate requests; services enforce scheduling rules; views display permitted information |
| Logistics | Shipment tracking dashboard | Controller retrieves tracking data; View presents milestones and status |
| Social media | Profile and post pages | Controllers coordinate feed/profile retrieval; View renders content |
| Enterprise software | Admin portals and reporting dashboards | MVC structures forms, filters, tables, and workflows |
The pattern is not restricted to these industries. It is a choice for organizing web applications, not a domain-specific technology.
13. Performance considerations
Memory
- Pass ViewModels containing only the data required by the page.
- Avoid loading huge collections into memory; use pagination.
- Avoid retaining request-specific data in singleton services.
- Use
AsNoTracking()for EF Core read-only queries when appropriate.
CPU
- Keep expensive computations out of Razor templates and controller actions.
- Profile before optimizing.
- Avoid repeated transformations of the same collection.
- Use caching for expensive, safe-to-cache results when invalidation rules are clear.
Scalability
- Use asynchronous I/O for database and network calls.
- Avoid
.Resultand.Wait()on asynchronous operations in request handling. - Keep application instances stateless where possible; store shared state in appropriate external services.
- Configure database connection pools and downstream timeouts deliberately.
Optimization
- Project only the columns required by the page.
- Add database indexes based on actual query patterns.
- Use pagination and bounded result sets.
- Cache static assets and configure appropriate HTTP cache headers.
- Measure database latency, response time, memory, and error rates before and after changes.
Warning:
asyncdoes not make CPU-bound work automatically faster. It helps keep threads available while asynchronous I/O is waiting.
14. Security considerations
Overposting and mass assignment
Binding an entity directly from an untrusted form can allow users to set fields they should not control.
Safer approach: Bind a purpose-built input model containing only permitted fields, then map validated values into the entity.
Cross-site request forgery (CSRF)
Cookie-authenticated applications can be vulnerable when an attacker causes a browser to submit an unwanted state-changing request.
Safer approach: Use anti-forgery validation for applicable form posts, use the MVC form tag helpers, and configure cookie and authentication protections correctly.
Cross-site scripting (XSS)
Untrusted data rendered as executable markup or script can run in another user's browser.
Safer approach: Keep Razor's default encoding, avoid rendering untrusted content with Html.Raw, and encode or sanitize data appropriately for the output context.
Broken authorization / insecure direct object references
A user may change an ID in a URL and attempt to access another user's record.
Safer approach: Authenticate the user and authorize access to the specific resource on every relevant request. Hiding a link in the UI is not authorization.
SQL injection
Concatenating untrusted strings into SQL can let input alter the query.
Safer approach: Use EF Core LINQ or parameterized SQL. Do not concatenate raw user input into SQL statements.
Sensitive data exposure
A page or error response may expose internal fields, secrets, or detailed exception information.
Safer approach: Use purpose-built ViewModels, avoid secrets in source control, use secure configuration, and display generic production error pages while logging diagnostic details securely.
Additional practices
- Enforce HTTPS.
- Validate input on the server.
- Apply authentication and authorization policies.
- Use least-privilege database credentials.
- Avoid logging passwords, tokens, or sensitive personal data.
- Keep dependencies and runtime patches current.
- Use safe file-upload validation if the application accepts uploads.
15. Ten common mistakes
| # | Mistake | Why it happens | How to fix it |
|---|---|---|---|
| 1 | Putting all logic in the controller | It is the first place developers handle a request | Delegate use cases to services and domain components |
| 2 | Putting database queries in views | Views appear close to the displayed data | Load data before rendering and pass a ViewModel |
| 3 | Binding database entities directly to forms | It seems convenient | Use input models and explicitly map permitted fields |
| 4 | Forgetting to check ModelState.IsValid | Developers assume attributes enforce all rules automatically | Validate before processing input |
| 5 | Missing anti-forgery validation | Form security is overlooked | Use anti-forgery protection for applicable state-changing forms |
| 6 | Treating client-side validation as sufficient | Invalid values are blocked in the browser | Always validate on the server |
| 7 | Calling .Result or .Wait() on async work | Synchronous code feels simpler | Use async/await end to end |
| 8 | Loading every database row | Small development datasets hide the problem | Add pagination and bounded queries |
| 9 | Assuming route IDs grant access | Route matching is confused with authorization | Authorize access to each resource |
| 10 | Using MVC as a folder convention only | The pattern is reduced to naming | Keep responsibilities separate and testable |
16. Production best practices
- Keep controllers thin. Coordinate requests; avoid turning actions into entire application workflows.
- Use dependency injection. Constructor injection makes required collaborators explicit.
- Use ViewModels for UI contracts. Do not expose persistence models indiscriminately.
- Validate on the server. Client-side checks are for user experience, not trust.
- Separate business rules from presentation. Rules should not depend on a particular Razor view.
- Use asynchronous I/O. Prefer EF Core's asynchronous query and save methods for database I/O.
- Propagate cancellation tokens. Honor request cancellation in supported downstream operations.
- Choose service lifetimes deliberately. A scoped service should not be captured by a singleton.
- Protect state-changing form submissions. Apply anti-forgery defenses where appropriate.
- Authorize every protected operation. Check both the user's permissions and access to the requested resource.
- Use parameterized database access. Avoid constructing SQL with untrusted input.
- Paginate large result sets. Bound memory, response size, and query cost.
- Project only required fields. Reduce data transfer and materialization overhead.
- Use
AsNoTracking()for read-only EF Core queries when appropriate. Tracking is useful when changes will be saved. - Use Post/Redirect/Get after successful form submissions. Reduce accidental duplicate posts on refresh.
- Log meaningful events. Use structured logging and avoid logging secrets or sensitive payloads.
- Handle exceptions centrally. Use production exception handling and avoid exposing stack traces to users.
- Keep secrets out of source control. Use user secrets locally and secure configuration in deployment.
- Test the important layers. Unit-test business behavior and integration-test routing, persistence, and HTTP responses.
- Use consistent status codes and result types. Communicate success, validation failures, and missing resources clearly.
- Keep Razor views focused. Use partial views and view components when they genuinely improve reuse.
- Profile before optimizing. Measure slow endpoints and database queries rather than guessing.
- Use explicit route constraints where useful. Make route intent clear, but do not confuse constraints with validation.
- Review accessibility. Use semantic HTML, associated labels, and understandable validation messages.
- Organize around features when complexity warrants it. Prefer discoverable code over unnecessary abstraction layers.
17. Interview questions
Beginner questions
1. What is MVC?
MVC is an architectural pattern that separates application data and rules, presentation, and request coordination into Model, View, and Controller responsibilities. In ASP.NET Core, controllers commonly handle HTTP requests and Razor views render HTML.
2. What are the three components of MVC?
- Model: Application data and/or domain concepts.
- View: Presentation template.
- Controller: Coordinates request handling and selects the response.
3. What is a controller in ASP.NET Core?
A controller groups related actions that respond to matching requests. It typically receives dependencies through DI, calls application services, and returns an action result.
4. What is a Razor view?
A .cshtml template that combines HTML with Razor syntax and C# expressions to render a response, often HTML.
5. What is an action method?
A method MVC can select and invoke for a request based on endpoint routing and MVC action-selection rules.
6. What does return View(model) do?
It returns a view result and supplies the model object to the view. MVC then locates and executes the view to produce the response.
7. What is routing?
Routing matches an incoming request to an endpoint using route patterns and applicable constraints. It helps select a controller action but does not authorize access.
8. What is model binding?
Model binding converts request values, such as route values, query parameters, and form fields, into .NET action parameters or model properties.
9. What is model validation?
It checks bound input against validation rules and records errors, commonly in ModelState. The action should check validity before processing a typical MVC form submission.
10. Can an MVC controller return JSON?
Yes. MVC controllers can return JSON or other response types, not only Razor views. Use the result type that matches the endpoint's purpose.
Intermediate questions
11. What is the difference between a Model and a ViewModel?
A Model represents application data or domain concepts. A ViewModel is shaped for a particular UI and contains the data that view needs. A ViewModel can prevent internal persistence fields from leaking into the presentation contract.
12. Why should controllers be thin?
Large controllers are hard to test and maintain. Thin controllers delegate use cases to services and focus on request coordination, response selection, and HTTP-specific behavior.
13. What is dependency injection in MVC?
DI supplies a controller's collaborators, usually through its constructor. It avoids manual construction of dependencies, makes dependencies explicit, and supports substitution in tests.
14. What is the difference between conventional routing and attribute routing?
Conventional routing defines shared route patterns, such as {controller=Home}/{action=Index}/{id?}. Attribute routing places route templates and HTTP method constraints on controllers or actions. Both can be used according to application needs.
15. Why use IActionResult?
It allows an action to return different result types, such as a view, redirect, not-found response, or bad request, through a common abstraction.
16. Why use AsNoTracking()?
EF Core tracking supports change detection for entities that may be updated. For read-only queries, AsNoTracking() can reduce tracking overhead. It is not always appropriate when the returned entities will be modified and saved through the same context.
17. What is the Post/Redirect/Get pattern?
After a successful form POST, the server redirects to a GET endpoint. Refreshing the resulting page then repeats the GET rather than resubmitting the original form. This helps reduce accidental duplicate submissions but does not replace idempotency or duplicate-operation protection.
18. How does validation work in MVC?
MVC binds incoming values and runs applicable validation. Errors are recorded in ModelState. The controller checks ModelState.IsValid, returns the form view with errors when invalid, and processes valid input through the appropriate service.
19. What is the role of middleware compared with MVC filters?
Middleware runs in the broader HTTP pipeline. MVC filters run at defined points in MVC action/result processing. Middleware suits application-wide HTTP concerns; filters suit MVC-specific cross-cutting concerns.
20. How do you protect MVC POST actions?
Use appropriate authentication and authorization, anti-forgery validation for applicable cookie-authenticated form submissions, server-side validation, and resource-level authorization. Use HTTPS and avoid trusting hidden form fields.
Advanced questions
21. Does MVC require every action to return a view?
No. Actions can return redirects, JSON, files, status codes, or other action results. The result depends on the endpoint's purpose.
22. How would you prevent overposting?
Bind a dedicated input model that exposes only editable fields. Validate it, authorize the operation, and map permitted values explicitly to the domain or persistence object. Avoid binding untrusted input directly to a sensitive entity.
23. How would you handle authorization for a resource identified by an ID?
Authenticate the caller, retrieve or otherwise identify the resource, and authorize the caller's access to that specific resource using policies or resource-based authorization. Do not assume knowing an ID grants permission.
24. How do you improve a slow MVC page?
Measure end-to-end latency and database query duration first. Inspect query plans, add justified indexes, project required fields, paginate results, use asynchronous I/O, and apply caching only where freshness and authorization semantics allow it.
25. How do you test MVC applications?
Unit-test business services and domain rules. Test controller behavior where it contains meaningful decisions. Use integration tests to verify routing, filters, model binding, validation, persistence, and HTTP responses together.
26. How would you structure a large MVC solution?
Separate responsibilities by feature or application layer according to complexity. Keep presentation, use-case coordination, domain rules, and persistence concerns appropriately separated. Avoid adding abstractions that do not solve a real problem.
27. What is the difference between an MVC controller and an API controller?
A traditional MVC controller commonly returns Razor views for browser pages, but it can also return data. An API controller is generally designed around HTTP data contracts and commonly uses [ApiController], automatic API validation behavior, and JSON responses. The distinction is about conventions and intended use, not an absolute restriction on return types.
28. How should errors be handled in production?
Use centralized exception handling, return safe error pages or appropriate API errors, and log diagnostic details securely. Do not expose stack traces, database details, credentials, or other sensitive information to users.
29. When should you use caching in MVC?
Cache stable or expensive results when the invalidation and authorization rules are understood. Choose appropriate server-side or HTTP caching, ensure user-specific data is not shared incorrectly, and measure whether caching improves the actual bottleneck.
30. When would you choose Razor Pages instead of MVC?
Razor Pages can be simpler when an application is primarily organized around individual pages and their handlers. MVC can be a natural fit when many related routes share controller-based coordination. Both support server-rendered ASP.NET Core applications; choose based on the app's organization and team needs.
18. Hands-on exercise
Exercise: Build a product catalog
Goal: Build an MVC product listing and details page.
Requirements
- Create a
Productmodel withId,Name,Price, andStockQuantity. - Create a
ProductListItemViewModelandProductDetailsViewModel. - Create a service interface with methods to list products and retrieve one product by ID.
- Implement the service using an in-memory collection first.
- Create
ProductsControllerwithIndexandDetailsactions. - Create Razor views to display the list and details.
- Return
NotFound()when the requested product does not exist. - Add a search form and validate the search input.
- Write tests for the service's lookup behavior and missing-product case.
- Replace the in-memory implementation with EF Core as a follow-up task.
Acceptance criteria
/Productsdisplays a list.- Selecting a product opens its details page.
- Invalid or missing IDs do not crash the application.
- Controllers do not contain data-access logic.
- Views do not query the database.
- Input is validated on the server.
Extension: Add pagination and explain how it changes database queries, response size, and performance.
19. Mini project: Product catalog administration
Project goal
Build a small admin portal that lists products, shows details, and supports creating and editing products.
Features
- Product listing with search and pagination
- Product details page
- Create and edit forms with validation
- EF Core persistence
- Service layer for application use cases
- Authentication and authorization for administrative actions
- Anti-forgery protection for form submissions
- Structured logging and centralized exception handling
- Integration tests for key HTTP flows
Suggested milestones
| Milestone | Deliverable |
|---|---|
| 1. Structure | MVC project, model/ViewModels, routes, and views |
| 2. Read operations | Product listing and details |
| 3. Write operations | Create and edit with server-side validation |
| 4. Persistence | EF Core context and migrations |
| 5. Security | Authentication, authorization, anti-forgery protection |
| 6. Quality | Logging, error handling, and automated tests |
| 7. Performance | Pagination, projection, query inspection |
Definition of done
The project is complete when a user with the correct permissions can manage products, invalid input is handled gracefully, unauthorized access is rejected, and the critical workflows have automated tests.
20. Quiz: 10 multiple-choice questions
Question 1
What does MVC stand for?
A. Model–View–Controller
B. Module–Variable–Class
C. Middleware–View–Configuration
D. Model–Validation–Cache
Correct answer: A
Explanation: MVC separates responsibilities into Model, View, and Controller.
Question 2
Which component typically coordinates an incoming MVC request?
A. Razor view
B. Controller
C. Database table
D. CSS file
Correct answer: B
Explanation: The controller action coordinates the request and chooses an appropriate response.
Question 3
What is the primary purpose of a ViewModel?
A. Store database passwords
B. Replace routing
C. Shape data for a particular UI
D. Disable validation
Correct answer: C
Explanation: A ViewModel contains the information a view needs and can avoid exposing internal persistence fields.
Question 4
Which file extension is commonly used for Razor views?
A. .razor.csproj
B. .html.cs
C. .config
D. .cshtml
Correct answer: D
Explanation: ASP.NET Core MVC views commonly use .cshtml.
Question 5
What does model binding do?
A. Converts supported request values into .NET parameters and objects
B. Generates database migrations automatically for every request
C. Authorizes every user
D. Compiles CSS
Correct answer: A
Explanation: Model binding reads request data and populates action parameters or model properties.
Question 6
What should a typical MVC form action do when ModelState.IsValid is false?
A. Ignore all errors
B. Return the form with validation errors
C. Delete the model
D. Redirect to a random page
Correct answer: B
Explanation: Returning the form lets the user correct invalid input. Server-side validation must remain authoritative.
Question 7
Why might AsNoTracking() be used for a read-only EF Core query?
A. It automatically authorizes the user
B. It encrypts all fields
C. It avoids change-tracking overhead when tracking is unnecessary
D. It removes all SQL queries
Correct answer: C
Explanation: No-tracking queries can reduce overhead when entities are only being read.
Question 8
What is a suitable defense against overposting?
A. Hide fields with CSS
B. Trust all posted entity properties
C. Disable server-side validation
D. Bind a purpose-built input model and map allowed fields
Correct answer: D
Explanation: A narrow input model limits which fields the user can submit for modification.
Question 9
What does Post/Redirect/Get help prevent?
A. Accidental resubmission of a successful POST when refreshing the resulting page
B. All unauthorized access
C. All database deadlocks
D. Every form validation error
Correct answer: A
Explanation: The redirect means refresh repeats the GET. Additional idempotency protections may still be needed for duplicate operations.
Question 10
Does every MVC action have to return a Razor view?
A. Yes, always
B. No, it may return JSON, a redirect, a file, or another result
C. Yes, unless the database is empty
D. Only in production
Correct answer: B
Explanation: MVC actions can return different result types according to the endpoint's purpose.
21. Summary
One-minute revision
MVC separates responsibilities:
- Model: application data and/or domain concepts.
- View: presentation, commonly a Razor
.cshtmlfile. - Controller: coordinates request handling and selects a response.
ASP.NET Core routing selects endpoints, model binding converts request values, validation records errors, DI supplies dependencies, and Razor renders HTML when a view result is returned.
Five-minute revision
- A browser sends a request.
- Middleware processes the request.
- Routing selects an endpoint.
- MVC binds request data and performs applicable validation.
- A controller action coordinates the use case through services.
- The action returns a result.
- If it is a view result, Razor renders HTML.
- Security must be enforced server-side through validation, authentication, authorization, anti-forgery defenses, and safe output handling.
- Performance depends on efficient queries, bounded result sets, asynchronous I/O, and measurement.
- Maintainable MVC applications keep presentation, request coordination, business rules, and persistence concerns appropriately separated.
Bullet-point summary
- MVC means Model–View–Controller.
- MVC is a pattern, not merely a folder structure.
- Models and ViewModels serve different purposes.
- Razor views focus on presentation.
- Controllers coordinate HTTP requests.
- Routing selects endpoints; it does not authorize resource access.
- Model binding and validation are related but distinct.
- Dependency injection makes dependencies explicit.
- Services can keep controllers thin.
- Production applications need deliberate security, performance, and testing.
Memory tricks
- M = Meaning: What data and rules does the application represent?
- V = Visuals: How should information be presented?
- C = Coordinator: What should happen for this request?
- Route → Bind → Validate → Execute → Respond: A useful simplified request-flow mnemonic.
- Controller coordinates; service performs the use case; view presents. This is a helpful default, not an inflexible rule for every application.
Flashcards
| Front | Back |
|---|---|
| What does MVC stand for? | Model–View–Controller |
| What is a ViewModel? | Data shaped for a particular view |
| What does routing do? | Selects a matching endpoint |
| What does model binding do? | Converts request values into .NET objects |
What does ModelState.IsValid indicate? | Whether binding and validation have reported errors |
| What does Razor render? | A template into a response, commonly HTML |
| Why use dependency injection? | To supply explicit, replaceable dependencies |
Why use AsNoTracking()? | To avoid unnecessary EF Core tracking for read-only queries |
22. Cheat sheet
| Need | Common MVC solution |
|---|---|
| Handle a browser request | Controller action |
| Render HTML | return View(model); |
| Redirect after POST | RedirectToAction(...) |
| Return 404 | NotFound() |
| Accept form input | Input/ViewModel + model binding |
| Validate form input | Data annotations + ModelState.IsValid |
| Protect applicable form POSTs | Anti-forgery token and validation |
| Access a service | Constructor injection |
| Select an endpoint | Conventional or attribute routing |
| Render dynamic content | Razor expressions and loops |
| Query read-only data | EF Core projection and possibly AsNoTracking() |
| Improve large lists | Pagination and bounded queries |
| Handle production errors | Centralized exception handling |
| Protect a record | Resource-level authorization |
| Test the request pipeline | ASP.NET Core integration tests |
Minimal MVC setup
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseRouting();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
This is a minimal routing illustration, not a complete production pipeline. A real application should also configure appropriate exception handling, HTTPS, static files, authentication, authorization, and other required middleware.
23. Comparison table
MVC vs Razor Pages vs Minimal APIs
| Aspect | MVC | Razor Pages | Minimal APIs |
|---|---|---|---|
| Main organization | Controllers and actions | Pages and page handlers | Route handlers |
| Typical UI | Server-rendered HTML | Server-rendered HTML | Often HTTP APIs, but not limited to them |
| Good fit | Applications with related controller actions | Page-focused applications | Lightweight HTTP endpoints and APIs |
| View handling | Razor views | Razor Pages | No built-in MVC view convention required |
| Request logic | Controller actions | Page handlers | Endpoint delegates/handlers |
| Complexity | Depends on architecture | Often intuitive for page-oriented work | Often concise for endpoints |
| Can use DI? | Yes | Yes | Yes |
MVC vs Web API controller
| Aspect | MVC controller | API-oriented controller |
|---|---|---|
| Common purpose | Browser workflows and HTML views | HTTP APIs and data contracts |
| Typical output | HTML, redirects, or other action results | JSON/data and HTTP status codes |
[ApiController] | Optional, depending on design | Commonly used |
| Validation behavior | Explicitly handle ModelState in typical MVC form flows | [ApiController] can automatically return HTTP 400 for invalid model state |
| Shared capabilities | Routing, DI, filters, authorization | Routing, DI, filters, authorization |
These are conventions rather than strict boundaries. ASP.NET Core MVC and API controllers share underlying infrastructure.
Model vs Entity vs ViewModel
| Aspect | Domain model | Persistence entity | ViewModel |
|---|---|---|---|
| Primary purpose | Represent domain concepts and rules | Represent stored data | Represent UI needs |
| Knows about UI? | Ideally no | Ideally no | Yes, for the relevant view |
| Maps to database? | Not necessarily | Usually | Usually not directly |
| Typical example | Order | ProductEntity | ProductDetailsViewModel |
24. Key takeaways
- MVC separates request coordination, presentation, and application data/rules.
- Controllers should coordinate rather than own every business rule.
- Views render data; they should not be the data-access layer.
- ViewModels create deliberate UI contracts.
- Routing, model binding, and validation are distinct steps.
- Dependency injection makes application dependencies easier to manage and test.
- MVC actions can return views, redirects, JSON, files, and other results.
- Security requires server-side validation and authorization, plus appropriate CSRF and output-encoding defenses.
- Production performance depends on efficient queries, bounded results, asynchronous I/O, and measurement.
- Choose MVC, Razor Pages, or Minimal APIs based on the application's needs rather than assuming one is universally best.
25. Revision checklist
Use this checklist before moving to the next topic.
- I can explain Model, View, and Controller in my own words.
- I understand the difference between an entity and a ViewModel.
- I can create a controller action that returns a view.
- I understand conventional and attribute routing.
- I can explain model binding and model validation.
- I can use dependency injection in a controller.
- I can explain the request lifecycle.
- I know when to return a view, redirect, JSON, or status code.
- I can describe common MVC security risks and defenses.
- I can explain when
AsNoTracking()and pagination help. - I can write a thin controller that calls a service.
- I can compare MVC with Razor Pages and Minimal APIs.
26. Further reading
Continue with these related roadmap topics on the Logic Lense / .NET Interview Ready learning platform:
- ASP.NET Core Fundamentals roadmap
- Logging abstractions (previous topic in this roadmap)
- Razor Pages (next topic in this roadmap)
- Dependency Injection
- Middleware in ASP.NET Core
- Configuration and
appsettings.json - Service Lifetimes
- Model Binding and Validation
- Routing in ASP.NET Core
- Filters in ASP.NET Core
- Authentication and Authorization
- Entity Framework Core
- REST API fundamentals
Last updated 10/23/2026
Your notes
Sign in to save personal notes on this topic — they'll sync across your devices.
Was this tutorial helpful?
Help us create more free learning resources. Learn more
