ASP.NET Core MVC Interview Question #50

What are best practices for designing MVC controllers and actions?

Controllers, Actions, Model Binding & Action Results Junior Beginner

Quick Interview Answer

Keep controllers focused on HTTP and application-flow concerns: accept input, validate it, call application services, and choose the response. Use dedicated ViewModels or input models rather than binding database entities directly, and use dependency injection instead of constructing infrastructure dependencies inside actions.

Detailed Explanation

Keep controllers focused on HTTP and application-flow concerns: accept input, validate it, call application services, and choose the response. Use dedicated ViewModels or input models rather than binding database entities directly, and use dependency injection instead of constructing infrastructure dependencies inside actions.

Use appropriate HTTP methods, anti-forgery protection for state-changing browser forms, Post/Redirect/Get after successful submissions, asynchronous I/O, cancellation tokens, and clear routing. Keep business rules and data-access logic outside controllers so actions remain small, testable, and maintainable.

Code Example

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(
    ProductEditViewModel model,
    CancellationToken cancellationToken)
{
    if (!ModelState.IsValid)
        return View(model);

    await _service.UpdateAsync(model, cancellationToken);

    TempData["Success"] = "Product updated.";
    return RedirectToAction(nameof(Index));
}