ASP.NET Core MVC Controllers

This document provides an in-depth guide to understanding and working with controllers in ASP.NET Core MVC applications. Controllers are a core component of the Model-View-Controller (MVC) architectural pattern, responsible for handling incoming requests, interacting with models, and selecting views to render.

What is a Controller?

In ASP.NET Core MVC, a controller is a class that:

Controller classes are typically placed in the Controllers folder of your ASP.NET Core project.

Creating a Controller

A controller is simply a public class that inherits from Microsoft.AspNetCore.Mvc.Controller. It's a convention to end controller class names with the suffix Controller.

Example: A Simple Controller


using Microsoft.AspNetCore.Mvc;

namespace MyWebApp.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View(); // Renders the Index.cshtml view
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";
            return View(); // Renders the About.cshtml view
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";
            return View(); // Renders the Contact.cshtml view
        }
    }
}
        

Controller Actions

Public methods within a controller class are called actions. These methods are invoked by the routing system when a matching HTTP request is received. Action methods must return an object that implements the IActionResult interface.

Common IActionResult Types

Routing and Action Selection

ASP.NET Core uses a flexible routing system to map incoming URLs to specific controller actions. The default routing convention typically follows the pattern: /ControllerName/ActionName/OptionalParameters.

For example, the URL /Home/About would invoke the About action on the HomeController.

Route Constraints and Attributes

You can customize routing using route templates and attributes. For instance, applying the [Route] attribute to a controller or action can define specific URL patterns.

Route Attribute Example

[Route("api/[controller]/[action]")]

This attribute can be applied to a controller class to set a base route for all its actions. For example, a controller named ProductsController would have routes like /api/Products/GetAll.

[HttpGet], [HttpPost], etc.

HTTP verb attributes can restrict an action to specific HTTP methods. For example, [HttpGet("details/{id}")].

Passing Data to Views

Controllers can pass data to views using several mechanisms:

Example: Using ViewData and ViewBag


using Microsoft.AspNetCore.Mvc;

public class ProductController : Controller
{
    public IActionResult Details(int id)
    {
        ViewData["ProductId"] = id;
        ViewBag.ProductName = "Example Product";
        // Fetch product details from a database or service
        var product = new { Id = id, Name = "Example Product", Price = 19.99 };
        return View(product); // Pass the product model to the view
    }
}
        

Handling Request Data

Controllers can receive data from requests in various ways:

Model Binding

ASP.NET Core's model binder automatically maps incoming request data to parameters in your action methods or to properties of a model object passed to the action.

Model Binding Example

public IActionResult Search(string q, int page = 1)

Here, q would be bound from the query string parameter ?q=..., and page would be bound from ?page=... or use the default value of 1.

public IActionResult Create([FromBody] Product newProduct)

The [FromBody] attribute instructs the model binder to read the request body, typically JSON, and deserialize it into the newProduct object.

Controller Base Classes

While inheriting directly from Controller is common, ASP.NET Core offers other base classes for specific scenarios:

Next Steps

Explore how to leverage controllers effectively in conjunction with models and views to build robust and maintainable web applications.