ASP.NET MVC quiz and interview questions
ASP.NET MVC is still everywhere in company code, and its ideas live on in ASP.NET Core. Interviews ask how a request is routed to a controller, how data reaches the view, how validation works and how to keep forms secure. Practise them here.
ASP.NET MVC: key concepts
- Model, View, Controller
- The controller handles the request and talks to the model (data and rules); the view renders HTML. Keeping them separate makes code easier to test and change.
- Routing
- Routes map URLs to controller actions, e.g. {controller=Home}/{action=Index}/{id?}. Attribute routing puts the route right on the action.
- Razor views
- .cshtml files mixing HTML with C# via @. Layouts hold the shared page shell; partial views are reusable pieces.
- Model binding and validation
- Form, route and query values are bound to action parameters. Data annotations like [Required] feed ModelState.IsValid.
- ViewData, ViewBag, TempData
- ViewData and ViewBag pass data to the current view. TempData survives one redirect — handy for success messages.
- Filters
- Authorization, action, result and exception filters run code around actions — e.g. [Authorize], logging or error handling.
All 55 ASP.NET MVC questions with answers
Try each one first, then open the answer. Making a class test? Use the test maker.
In MVC, which part handles the incoming request and chooses what to return?
- A. Model
- B. View
- C. Controller
- D. Router
Show answer
C. Controller — The controller's action receives the request, works with the model and returns a result such as a view or a redirect.
What does the View do in MVC?
- A. Stores data
- B. Renders the user interface (HTML)
- C. Handles routing
- D. Talks to the database
Show answer
B. Renders the user interface (HTML) — Views should only display data passed to them. Business logic belongs in the model or services.
With the default route below, which action handles GET /Products/Details/7?
{controller=Home}/{action=Index}/{id?}- A. HomeController.Index()
- B. ProductsController.Details(id: 7)
- C. ProductsController.Index(7)
- D. DetailsController.Products(7)
Show answer
B. ProductsController.Details(id: 7) — The first segment is the controller (Products), the second the action (Details), and 7 binds to the optional id.
Which one survives a redirect?
- A. ViewData
- B. ViewBag
- C. TempData
- D. Local variables
Show answer
C. TempData — TempData is kept until it's read on the next request, so it works for "Saved!" messages after RedirectToAction.
What is Razor?
- A. A JavaScript framework
- B. The view syntax that mixes HTML and C# using @
- C. A database
- D. A test runner
Show answer
B. The view syntax that mixes HTML and C# using @ — In a .cshtml file, @Model.Name or @foreach (...) runs C# while the rest is plain HTML.
What HTML does this Razor render?
@{ var n = 3; } <p>@(n * 2)</p>- A. <p>n * 2</p>
- B. <p>6</p>
- C. <p>@(n * 2)</p>
- D. <p>3</p>
Show answer
B. <p>6</p> — @( ... ) evaluates the C# expression and writes the result: 6.
What is a partial view for?
- A. Hiding parts of a page
- B. A reusable piece of markup used inside other views
- C. Loading pages faster
- D. Partial page caching only
Show answer
B. A reusable piece of markup used inside other views — E.g. _ProductCard.cshtml rendered in several pages with <partial name="_ProductCard" model="p" />.
What does a layout page do?
- A. Defines routes
- B. Provides the shared page shell (header, footer) with @RenderBody() for each view
- C. Validates forms
- D. Stores CSS only
Show answer
B. Provides the shared page shell (header, footer) with @RenderBody() for each view — _Layout.cshtml avoids repeating the same header and footer in every view.
What is model binding?
- A. Linking two models
- B. Automatically filling action parameters from form, route and query values
- C. Binding CSS to models
- D. Mapping models to tables
Show answer
B. Automatically filling action parameters from form, route and query values — public IActionResult Save(Product p) gets p.Name, p.Price… from the posted form fields with matching names.
What's missing from this action?
[HttpPost] public IActionResult Save(Product p) { _db.Products.Add(p); _db.SaveChanges(); return RedirectToAction("Index"); }- A. Nothing
- B. A ModelState.IsValid check — invalid data gets saved
- C. It must return View()
- D. Save must be async
Show answer
B. A ModelState.IsValid check — invalid data gets saved — Validation attributes only populate ModelState; you must check it: if (!ModelState.IsValid) return View(p);
What is the security problem with this form-handling action?
[HttpPost] public IActionResult Delete(int id) { _repo.Delete(id); return RedirectToAction("Index"); }- A. Delete must be HttpGet
- B. No anti-forgery token check, so it's open to CSRF attacks
- C. id should be a string
- D. There's no problem
Show answer
B. No anti-forgery token check, so it's open to CSRF attacks — Add [ValidateAntiForgeryToken] (and the token in the form) so another site can't trick a logged-in user into posting.
Which filter type runs first in the MVC pipeline?
- A. Exception filters
- B. Result filters
- C. Authorization filters
- D. Action filters
Show answer
C. Authorization filters — Authorization filters decide whether the request may continue at all, before model binding and the action run.
Which return type sends JSON to the client?
- A. View()
- B. Json(data) / JsonResult
- C. Content("...")
- D. Redirect()
Show answer
B. Json(data) / JsonResult — return Json(products); serializes the object to JSON with the right content type.
Why redirect after a successful POST (Post/Redirect/Get)?
- A. To load faster
- B. So refreshing the page doesn't re-submit the form
- C. It's required by HTTP
- D. To clear the cache
Show answer
B. So refreshing the page doesn't re-submit the form — After a redirect the browser's last request is a GET, so F5 reloads the result page instead of posting the form again.
What are Areas used for?
- A. Map coordinates
- B. Splitting a large app into sections (e.g. Admin, Shop) with their own controllers and views
- C. CSS layout
- D. Database regions
Show answer
B. Splitting a large app into sections (e.g. Admin, Shop) with their own controllers and views — Areas keep big MVC apps organised: /Admin/Users and /Shop/Products live in separate folders.
What is a strongly typed view?
- A. A view without C#
- B. A view that declares @model, giving IntelliSense and compile-time checks
- C. A view with no layout
- D. A cached view
Show answer
B. A view that declares @model, giving IntelliSense and compile-time checks — @model ProductViewModel lets you write @Model.Price safely instead of using untyped ViewBag.
What does [HttpPost] on an action do?
- A. Makes it faster
- B. Restricts it to POST requests
- C. Posts data to another site
- D. Enables caching
Show answer
B. Restricts it to POST requests — A GET and a POST action can share a name: one shows the form, the other handles the submission.
How should a controller get its services (repositories, email senders…)?
- A. new them inside each action
- B. Through constructor injection from the DI container
- C. Static global variables
- D. Reflection
Show answer
B. Through constructor injection from the DI container — Constructor injection keeps controllers testable — you can pass fakes in unit tests.
What is the difference between return View() and return RedirectToAction()?
- A. None
- B. View renders HTML in this response; RedirectToAction sends a 302 so the browser makes a new request
- C. Redirect is faster
- D. View changes the URL
Show answer
B. View renders HTML in this response; RedirectToAction sends a 302 so the browser makes a new request — Use RedirectToAction after successful POSTs, and View() when you want to show a page (e.g. a form with errors).
Which attribute makes a property required in model validation?
- A. [Key]
- B. [Required]
- C. [Display]
- D. [NotMapped]
Show answer
B. [Required] — [Required], [StringLength], [Range] and [EmailAddress] are data annotations that drive validation messages.
What is a ViewModel?
- A. The database entity
- B. A class shaped for one view, holding exactly the data that page needs
- C. A Razor file
- D. A controller base class
Show answer
B. A class shaped for one view, holding exactly the data that page needs — ProductPageViewModel can combine the product, its reviews and a list of categories without exposing your entity.
How do you read TempData without removing it?
- A. TempData.Get()
- B. TempData.Peek("key") (or Keep after reading)
- C. TempData.Clear()
- D. You can't
Show answer
B. TempData.Peek("key") (or Keep after reading) — Reading TempData normally marks it for deletion; Peek reads without marking, Keep() keeps it for another request.
Which URL calls this action?
[Route("shop/{category}/{id:int}")] public IActionResult Item(string category, int id) { ... }- A. /Item?category=books&id=5
- B. /shop/books/5
- C. /shop/books/five
- D. /books/shop/5
Show answer
B. /shop/books/5 — Attribute routing maps /shop/books/5 to category = "books", id = 5. The :int constraint rejects "five".
What does a route constraint like {id:int} do?
- A. Converts strings to int
- B. Only matches the route when the value is an integer
- C. Makes id required
- D. Encrypts the id
Show answer
B. Only matches the route when the value is an integer — With {id:int}, /items/abc doesn't match this route and can fall through to another route or a 404.
What does @RenderSection("Scripts", required: false) in a layout do?
- A. Loads all scripts
- B. Lets each view optionally put content (e.g. page scripts) into that spot of the layout
- C. Renders partial views
- D. Bundles JavaScript
Show answer
B. Lets each view optionally put content (e.g. page scripts) into that spot of the layout — A view adds @section Scripts { <script>…</script> } and it appears where the layout renders the section.
What is _ViewStart.cshtml for?
- A. The home page
- B. Code that runs before every view — usually setting the default Layout
- C. Routing
- D. Validation
Show answer
B. Code that runs before every view — usually setting the default Layout — @{ Layout = "_Layout"; } in _ViewStart saves repeating it in every view.
In ASP.NET Core MVC, what goes in _ViewImports.cshtml?
- A. Images
- B. Shared @using directives and @addTagHelper lines for all views in the folder
- C. CSS
- D. Routes
Show answer
B. Shared @using directives and @addTagHelper lines for all views in the folder — It avoids repeating namespaces and tag helper registrations in every view.
What is a tag helper such as asp-for or asp-action?
- A. A JavaScript plugin
- B. Server-side code that renders HTML attributes, e.g. <a asp-action="Details"> creates the right URL
- C. A CSS framework
- D. A view model
Show answer
B. Server-side code that renders HTML attributes, e.g. <a asp-action="Details"> creates the right URL — Tag helpers replace many HTML helpers (@Html.ActionLink) with HTML-like syntax that stays in sync with routes.
What replaced child actions (Html.Action) for reusable widgets in ASP.NET Core?
- A. Partial views only
- B. View components
- C. Middleware
- D. Areas
Show answer
B. View components — A view component (e.g. a shopping-cart summary) has its own logic and view, and can be invoked from any layout.
What does [Authorize] on a controller do?
- A. Logs requests
- B. Requires a signed-in user for its actions
- C. Encrypts responses
- D. Validates models
Show answer
B. Requires a signed-in user for its actions — Add roles or policies, e.g. [Authorize(Roles = "Admin")], and use [AllowAnonymous] for public actions like Login.
What is overposting (mass assignment)?
- A. Posting too often
- B. An attacker adds extra form fields (e.g. IsAdmin=true) that model binding writes to your entity
- C. Large file uploads
- D. Slow forms
Show answer
B. An attacker adds extra form fields (e.g. IsAdmin=true) that model binding writes to your entity — Bind only to a ViewModel with the editable fields (or use [Bind] carefully) instead of binding entities directly.
What is the security risk in this view?
<div>@Html.Raw(Model.Comment)</div>- A. None
- B. Cross-site scripting — user input is output without HTML encoding
- C. It's slow
- D. Model can't be used here
Show answer
B. Cross-site scripting — user input is output without HTML encoding — @Model.Comment is encoded automatically. Html.Raw turns encoding off, so a comment containing <script> would run.
How does client-side validation work in MVC?
- A. It replaces server validation
- B. Data annotations render data-val-* attributes that jQuery unobtrusive validation checks in the browser
- C. It uses cookies
- D. It's only for passwords
Show answer
B. Data annotations render data-val-* attributes that jQuery unobtrusive validation checks in the browser — It gives instant feedback, but always validate again on the server — client checks can be bypassed.
What does the [Remote] validation attribute do?
- A. Validates on a remote server farm
- B. Calls an action via AJAX to check a value, e.g. whether a username is taken
- C. Disables validation
- D. Validates files
Show answer
B. Calls an action via AJAX to check a value, e.g. whether a username is taken — [Remote("IsUsernameFree", "Account")] checks availability as the user types.
Why make actions async (async Task<IActionResult>)?
- A. To render faster HTML
- B. To free the thread while waiting for the database or APIs, so the server handles more requests
- C. To run on the client
- D. It's required
Show answer
B. To free the thread while waiting for the database or APIs, so the server handles more requests — await _db.Orders.ToListAsync() returns the thread to the pool during the database call.
What does [NonAction] do on a public controller method?
- A. Makes it private
- B. Stops it from being reachable as an action via a URL
- C. Disables logging
- D. Makes it async
Show answer
B. Stops it from being reachable as an action via a URL — Public methods on controllers are actions by default; [NonAction] opts a helper method out.
What does [ActionName("Delete")] on a method called DeleteConfirmed do?
- A. Renames the C# method
- B. Exposes it under the action name Delete in URLs
- C. Deletes the action
- D. Adds a confirmation dialog
Show answer
B. Exposes it under the action name Delete in URLs — It lets a GET Delete and a POST DeleteConfirmed share the URL /Products/Delete/5 despite C# needing different signatures.
How do you show a friendly error page for unhandled exceptions in production?
- A. Let the stack trace show
- B. Use exception-handling middleware/filters (e.g. UseExceptionHandler("/Error")) and log the details
- C. Wrap every line in try/catch
- D. Disable errors
Show answer
B. Use exception-handling middleware/filters (e.g. UseExceptionHandler("/Error")) and log the details — Users see a clean page; developers see full details in logs. Never show stack traces in production.
What does an exception filter do?
- A. Filters SQL
- B. Runs when an action throws, so you can log it and return a custom result
- C. Removes exceptions
- D. Validates models
Show answer
B. Runs when an action throws, so you can log it and return a custom result — Classic MVC had [HandleError]; ASP.NET Core uses IExceptionFilter or middleware.
What does response caching ([ResponseCache] / OutputCache) do?
- A. Caches database rows
- B. Lets clients, proxies or the server reuse a response for a time instead of re-running the action
- C. Stores session data
- D. Minifies HTML
Show answer
B. Lets clients, proxies or the server reuse a response for a time instead of re-running the action — Great for public pages that change rarely; never cache personalised pages publicly.
Which helper creates a link to another action?
- A. @Html.TextBoxFor
- B. @Html.ActionLink("Details", "Details", new { id = 5 })
- C. @Html.Partial
- D. @Html.Raw
Show answer
B. @Html.ActionLink("Details", "Details", new { id = 5 }) — In ASP.NET Core you'd usually write <a asp-action="Details" asp-route-id="5">Details</a>.
What do bundling and minification do?
- A. Compress images
- B. Combine and shrink CSS/JS files to cut requests and download size
- C. Encrypt scripts
- D. Bundle NuGet packages
Show answer
B. Combine and shrink CSS/JS files to cut requests and download size — Fewer, smaller files load faster. Modern apps often use a front-end build tool for this.
In what order does a request flow through classic ASP.NET MVC?
- A. View → Controller → Routing
- B. Routing → controller creation → action filters → action → result → view rendering
- C. Controller → Routing → View
- D. Model → View → Controller
Show answer
B. Routing → controller creation → action filters → action → result → view rendering — Knowing the pipeline tells you where to plug in auth, logging or caching.
The form posts Quantity = "abc". What is ModelState.IsValid?
public class OrderForm { [Range(1, 10)] public int Quantity { get; set; } } [HttpPost] public IActionResult Order(OrderForm form) => Ok(ModelState.IsValid);- A. true
- B. false
- C. An exception is thrown
- D. null
Show answer
B. false — "abc" can't bind to an int, so a model-binding error is added and IsValid is false (Quantity stays 0).
What does return PartialView() return?
- A. A whole page with layout
- B. Only the partial's HTML, without the layout — useful for AJAX updates
- C. JSON
- D. A redirect
Show answer
B. Only the partial's HTML, without the layout — useful for AJAX updates — JavaScript can fetch the partial and swap it into the page.
What is the difference between ViewData and ViewBag?
- A. ViewBag survives redirects
- B. ViewData is a dictionary (ViewData["Title"]); ViewBag is a dynamic wrapper over the same data (ViewBag.Title)
- C. ViewData is for JSON
- D. They store different data
Show answer
B. ViewData is a dictionary (ViewData["Title"]); ViewBag is a dynamic wrapper over the same data (ViewBag.Title) — Both last for the current request only. Prefer strongly typed view models for anything important.
What does scaffolding do in Visual Studio?
- A. Builds Docker images
- B. Generates a controller and CRUD views from a model
- C. Creates unit tests
- D. Deploys the app
Show answer
B. Generates a controller and CRUD views from a model — It's a fast start for admin screens; review the generated code (e.g. for overposting) before shipping.
The page shows the old value after a successful POST and the user presses F5. What happens?
[HttpPost] public IActionResult Save(ProductVm vm) { _service.Save(vm); return View(vm); }- A. Nothing
- B. The browser re-submits the form and the product is saved again
- C. The page goes blank
- D. A 404
Show answer
B. The browser re-submits the form and the product is saved again — Return RedirectToAction("Details", new { id }) after a successful POST (Post/Redirect/Get).
Where do Razor views for ProductsController live by default?
- A. /Pages/Products
- B. /Views/Products/ (then /Views/Shared/)
- C. /wwwroot/Products
- D. /Controllers/Views
Show answer
B. /Views/Products/ (then /Views/Shared/) — View discovery looks in Views/{Controller}/ and then Views/Shared/ for the action's view name.
What does [ValidateAntiForgeryToken] check?
- A. The user's password
- B. That the posted form contains the token issued with the page, blocking cross-site request forgery
- C. File types
- D. Model validity
Show answer
B. That the posted form contains the token issued with the page, blocking cross-site request forgery — Forms built with tag helpers include the token automatically; AJAX posts must send it in a header.
Why prefer ASP.NET Core MVC over classic ASP.NET MVC 5 for new work?
- A. MVC 5 is faster
- B. Core is cross-platform, faster, has built-in DI and is actively developed
- C. Core has no Razor
- D. MVC 5 supports Linux
Show answer
B. Core is cross-platform, faster, has built-in DI and is actively developed — MVC 5 runs only on .NET Framework (Windows) and gets maintenance fixes only.
What is the purpose of a display or editor template?
- A. Email templates
- B. A reusable partial that renders a type the same way everywhere (e.g. all Money values)
- C. Page layouts
- D. Validation rules
Show answer
B. A reusable partial that renders a type the same way everywhere (e.g. all Money values) — Put Money.cshtml in Views/Shared/DisplayTemplates and @Html.DisplayFor(m => m.Price) uses it.
How can one action serve both full pages and AJAX requests?
- A. It can't
- B. Check whether the request is AJAX (e.g. the X-Requested-With header) and return a partial instead of the full view
- C. Use two databases
- D. Disable the layout globally
Show answer
B. Check whether the request is AJAX (e.g. the X-Requested-With header) and return a partial instead of the full view — Many apps add an IsAjaxRequest() extension for this.
What is the default action if a URL only names the controller, e.g. /Products?
- A. Details
- B. Index
- C. Home
- D. List
Show answer
B. Index — The default route sets action=Index, so /Products → ProductsController.Index().
Where should business rules live in an MVC app?
- A. In the views
- B. In services/domain classes, keeping controllers thin
- C. In the layout
- D. In JavaScript only
Show answer
B. In services/domain classes, keeping controllers thin — Thin controllers that delegate to services are easier to test and reuse from APIs or background jobs.
More subjects
Need software for your business instead? I'm an AI automation & full-stack developer — see what I build.