ASP.NET MVC interview questions and answers
ASP.NET MVC interview questions follow one HTTP request through the framework: a route picks a controller and action, model binding turns form fields into a typed object, validation fills ModelState, filters run around the action, and an action result renders a Razor view or redirects. Interviewers check that you know each stage well enough to debug it, plus the security habits MVC expects of you, such as anti-forgery tokens and view models that block overposting. For maintenance roles, expect questions on moving a classic MVC 5 app to ASP.NET Core MVC.
By Evin JohnPublished 8 min read
Which ASP.NET MVC are they asking about?
Two frameworks share the name. Classic ASP.NET MVC (version 5 is the last major release) runs on .NET Framework on top of System.Web and IIS. ASP.NET Core MVC runs on modern .NET and merges MVC and Web API into one controller model. Most concepts carry over, so interviewers often ask them without saying which one they mean; it helps to say "in MVC 5 this works one way, in Core it works another" where they differ. This page stays on the MVC pattern itself. Dependency injection lifetimes, the middleware pipeline, EF Core and minimal APIs are covered in .NET interview questions.
- RoutingThe URL is matched against conventional routes or attribute routes to choose a controller and action, with route values such as
id. - Controller and action selectionThe controller is created (through DI in Core) and action selectors such as HttpGet and HttpPost narrow the candidates.
- Model binding and validationParameters are filled from route values, the query string, form fields or the body, then validated into ModelState.
- Filters and actionAuthorization, action and exception filters wrap the action method, which returns an action result.
- Result executionA ViewResult finds and renders a Razor view inside its layout; other results redirect, return JSON, a file or a status code.
Fundamentals: controllers, routing and views
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Explain Model, View and Controller in this framework. | Pattern | The model is the data and rules (often a view model shaped for one screen), the view is the Razor template that renders it, and the controller handles the request, calls services and chooses a result. Controllers stay thin. |
| What does an action method return? | Action results | An IActionResult (ActionResult in MVC 5): View, PartialView, RedirectToAction, Json, Content, File, NotFound or a status code. The result object, not the action, writes the response. |
| Conventional routing versus attribute routing? | Routing | Conventional routes are templates such as {controller}/{action}/{id?} defined once. Attribute routes sit on controllers and actions and suit APIs and irregular URLs. Both can coexist; order and constraints decide ties. |
| ViewData, ViewBag and TempData? | Passing data | ViewData is a dictionary and ViewBag is a dynamic wrapper over the same data, both living for one request. TempData survives until it is read, usually across one redirect, and is stored in a cookie or session. |
| What is a strongly typed view? | Razor | A view that declares @model SomeViewModel, giving compile-time checking and IntelliSense instead of string keys in ViewBag. |
| What do layouts and sections do? | Views | A layout is the shared page shell with RenderBody where each view's content goes; sections let a view push content, such as page scripts, into named slots in the layout. |
| Partial view or view component? | Reuse | A partial renders a piece of markup with the model you pass it. A view component (Core) has its own logic and data access, replacing child actions from MVC 5. |
| HTML helpers versus tag helpers? | Markup generation | Helpers like Html.TextBoxFor are C# calls in Razor. Tag helpers (Core) look like HTML attributes, such as asp-for and asp-action, and read more naturally. Both generate names that model binding understands. |
| How does MVC find a view? | View location | By convention: Views/<Controller>/<Action>.cshtml, then Views/Shared. You can pass a name or path to View() to override it, and areas add their own folders. |
| What are areas? | Large apps | A way to split a big app into sections (admin, billing) with their own controllers, views and routes, selected by an area route value. |
Model binding and validation questions
public class BookingForm : IValidatableObject
{
[Required, StringLength(40, MinimumLength = 2)]
public string Guest { get; set; }
[Required, EmailAddress]
public string Email { get; set; }
[Range(1, 8)]
public int Rooms { get; set; }
public DateTime CheckIn { get; set; }
public DateTime CheckOut { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
if (CheckOut <= CheckIn)
yield return new ValidationResult("Check-out must be after check-in.", new[] { "CheckOut" });
}
}
static void Check(string label, BookingForm form)
{
var errors = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(form, new ValidationContext(form), errors, true);
Console.WriteLine(label + " valid=" + valid);
foreach (var e in errors)
Console.WriteLine(" " + string.Join(",", e.MemberNames) + ": " + e.ErrorMessage);
}
var day = new DateTime(2026, 3, 10);
Check("A", new BookingForm { Guest = "J", Email = "nope", Rooms = 0, CheckIn = day, CheckOut = day });
Check("B", new BookingForm { Guest = "Jo", Email = "jo@example.com", Rooms = 2, CheckIn = day, CheckOut = day });
// A valid=False
// Guest: The field Guest must be a string with a minimum length of 2 and a maximum length of 40.
// Email: The Email field is not a valid e-mail address.
// Rooms: The field Rooms must be between 1 and 8.
// B valid=False
// CheckOut: Check-out must be after check-in.- Why does form A not report the date error? The validator runs property attributes first and calls IValidatableObject.Validate only if they all pass. A user can fix three fields, submit, and then meet a fourth error. Interviewers like candidates who know this and mention it in UX terms.
- What is ModelState and when do you check it? A dictionary of bound values and errors per field. Check
ModelState.IsValidat the top of a POST action and return the same view with the model, so the form re-renders with messages. API controllers in Core can do this automatically with the ApiController attribute. - Where does model binding look for values? Route values, the query string and form fields for simple types; the request body for complex types in APIs. Attributes like FromRoute, FromQuery, FromForm and FromBody pin the source when ambiguity would cause bugs.
- What is overposting and how do you stop it? A user adds extra form fields, such as IsAdmin, and binding sets them on your entity. Bind to a view model that has only the editable fields, then map to the entity. Bind include lists work but are easy to forget when the model grows.
- How does client-side validation work? The helpers emit data-val attributes from your annotations, and the unobtrusive validation script reads them in the browser. It is a convenience only; the server must validate again.
- How do you write a custom validation attribute? Derive from ValidationAttribute and override IsValid; implement client-side support separately if the rule must also run in the browser. Use IValidatableObject for rules that compare fields.
- What is remote validation? An attribute that calls an action over Ajax while the user types, typically to check that a username is free. The server still has to enforce uniqueness on submit, because the check can race.
- How do you bind a list of items from a form? Name inputs with indexes, like
Lines[0].QtyandLines[1].Qty. Gaps in the index can stop binding unless you use the index-field convention.
Filters and request pipeline questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Which filter types exist and in what order do they run? | Pipeline | Authorization first, then (in Core) resource filters, then action filters around the action, exception filters for unhandled errors, and result filters around rendering. |
| Global, controller or action scope? | Registration | Filters can be registered globally, on a controller, or on one action. Scope affects order: global wraps controller wraps action, unless an explicit Order changes it. |
| Filter or middleware? | Design | Middleware sees every request, including static files, and knows nothing about actions. A filter knows the action, its arguments and ModelState. Logging every request is middleware; validating an action's arguments is a filter. |
| How do you handle exceptions in MVC? | Errors | A global exception handler or exception filter returns a friendly error view and logs details. Showing a stack trace to users is a configuration mistake that leaks internals. |
| What does the Authorize attribute do? | Security | It runs an authorization filter that requires an authenticated user, optionally in a role or meeting a policy. AllowAnonymous opts out for one action, such as login. |
| How would you add timing to every action? | Practical filter | An action filter that starts a stopwatch in OnActionExecuting and logs in OnActionExecuted with the controller and action names. |
Security questions MVC interviewers ask
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(BookingForm form)
{
if (!ModelState.IsValid)
return View(form); // same view, errors shown next to fields
int id = await _bookings.CreateAsync(form.Guest, form.Email, form.Rooms, form.CheckIn, form.CheckOut);
TempData["Notice"] = "Booking saved.";
return RedirectToAction(nameof(Details), new { id }); // refresh will not resubmit
}- What does ValidateAntiForgeryToken protect against? Cross-site request forgery. The form carries a hidden token tied to a cookie, and a forged request from another site cannot read and include it. In Core, form tag helpers add the token automatically.
- How does Razor protect against XSS?
@output is HTML-encoded by default.Html.Rawturns that off and should only wrap trusted, sanitized markup. - What is an open redirect and how do you avoid one? A login page that redirects to any
returnUrlcan send users to a phishing site. Check withUrl.IsLocalUrlor use LocalRedirect. - Why Post/Redirect/Get? Redirecting after a successful POST means a browser refresh repeats the GET, not the purchase. TempData carries the success message across the redirect.
- What do you not put in hidden fields? Prices, roles or anything the server must trust. Hidden fields are user input like any other.
Senior and migration scenarios
| Scenario | What to say you would check | Direction |
|---|---|---|
| Moving an MVC 5 app to ASP.NET Core MVC. | Use of HttpContext.Current, Global.asax events, web.config settings, child actions, bundling and custom HTTP modules. | Port incrementally where possible; map modules to middleware, child actions to view components, web.config to appsettings, and test route by route. |
| A list page gets slower as data grows. | Whether the view lazy-loads related data per row, and whether paging happens in SQL or in memory. | Load what the view needs in one query into a view model; page in the database. |
| Users report double orders. | Missing Post/Redirect/Get, buttons that can be clicked twice, no idempotency on the server. | PRG, disable the button on submit, and an idempotency key or unique constraint on the server. |
| TempData message sometimes missing. | Whether something reads TempData earlier, or the provider (cookie or session) is not configured or the cookie is too large. | Read it once in the target view; use Keep or Peek when it must survive another request. |
| Large file uploads fail. | Request size limits in the server and framework, and buffering of the whole file in memory. | Raise limits deliberately for that action only and stream to storage. |
| A controller has grown to two thousand lines. | Business rules in actions, duplicated queries, untestable code. | Move logic into services, keep actions to binding, calling and choosing a result, and add tests around the services. |
Fictional example
- Interviewer
- A user submits the booking form to POST /bookings/create. Walk me through what the framework does.
- Candidate
- Routing matches the URL to BookingsController.Create, and the HttpPost selector picks the POST overload. Before the action runs, the anti-forgery filter compares the form token with the cookie and rejects the request if they do not match. Model binding builds a BookingForm from the form fields, and validation fills ModelState from the annotations and then the cross-field rule. In the action I check ModelState.IsValid; if it fails I return the same view so the errors appear next to each field. If it passes I call the booking service, put a notice in TempData and redirect to the details page, so a refresh does not create a second booking. The redirect result sends a 302, and the browser's GET renders the details view inside the layout.
How to prepare for ASP.NET MVC questions
- Build one CRUD screen end to end: list, create, edit and delete with view models, validation, PRG and TempData messages. Then break each stage on purpose and read the error.
- Trace a request: add a logging action filter and middleware, and note the order of their log lines for a valid and an invalid form.
- Rehearse security answers: CSRF, XSS encoding, overposting and open redirects, each with the one-line fix.
- If the job is legacy work: list what changes from MVC 5 to Core (hosting, configuration, child actions, bundling, DI) and practice explaining one migration step you would take first.
- Talk through your own app: interviewers often ask you to sketch the folders, layers and one tricky bug from a project on your résumé.
Data access questions often follow in the same loop; ADO.NET interview questions covers readers, DataSets, parameters and pooling. Many MVC apps from the same era also host an AngularJS front end on their views, which AngularJS interview questions covers, and language topics sit in C# interview questions.
Lifecycle questions are easy to answer out of order once nerves kick in. Natively, an AI interview assistant for Mac and Windows, transcribes a practice round on your computer so you can see whether you mentioned validation before the action ran or skipped a stage. While you rehearse, it can read a controller or a stack trace from a screenshot and suggest points to cover, and with Pro or the free trial it uses the résumé and job description you add to tailor suggestions. The transcript and notes are kept for you to go over afterward.
Questions people ask
What ASP.NET MVC questions are asked in interviews?
The request lifecycle, conventional versus attribute routing, action results, ViewData versus ViewBag versus TempData, model binding and validation, filters, Razor layouts and partials, CSRF protection and overposting.
What is the difference between ViewBag, ViewData and TempData?
ViewData is a dictionary and ViewBag a dynamic wrapper over it, both for one request. TempData survives until it is read, usually across one redirect.
Is ASP.NET MVC different from ASP.NET Core MVC?
Yes. Classic ASP.NET MVC runs on .NET Framework and System.Web; ASP.NET Core MVC runs on modern .NET and merges MVC and Web API. Most concepts carry over, but hosting, configuration and some features differ.
How do I prepare for an ASP.NET MVC interview?
Build one CRUD screen with view models, validation, Post/Redirect/Get and TempData, trace the order of filters and middleware, and rehearse CSRF, XSS and overposting answers.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
