ASP.NET Core MVC Controllers

Your comprehensive guide to mastering controllers in ASP.NET Core MVC

Understanding Controllers in ASP.NET Core MVC

Controllers are the heart of an ASP.NET Core MVC application. They handle incoming requests, interact with models to fetch or manipulate data, and select views to render the response. This tutorial delves into the fundamental concepts and features of controllers.

What is a Controller?

A controller is a class that inherits from Controller or ControllerBase. It contains public methods called action methods, which are responsible for processing specific requests. Action methods typically return an IActionResult, which represents the result of the action, such as rendering a view, returning JSON data, or redirecting to another page.

Creating a Simple Controller

Let's create a basic controller named HomeController:

Example: HomeController.cs


using Microsoft.AspNetCore.Mvc;

namespace MyMvcApp.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            // This action method returns a view
            return View(); 
        }

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

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

Action Methods

Action methods are public methods within a controller that perform specific tasks. They are identified by their name, which is typically used in the URL to invoke them. For example, in the URL /Home/Index, Home refers to the controller and Index refers to the action method.

Action Method Return Types

Action methods can return various types of results:

View Data and View Bags

Controllers use ViewData and ViewBag to pass data to views.

Example: Passing Data to a View


public IActionResult Details(int id)
{
    var product = GetProductById(id); // Assume this method fetches product data

    // Using ViewData
    ViewData["ProductName"] = product.Name;
    ViewData["ProductPrice"] = product.Price;

    // Using ViewBag
    ViewBag.ProductDescription = product.Description;

    return View(product); // Pass the model to the view as well
}
            

Model Binding

ASP.NET Core MVC automatically binds incoming request data (form values, route data, query strings) to parameters of your action methods. This process is called model binding.

Example: Model Binding


public IActionResult Search(string query, int page = 1)
{
    // 'query' and 'page' are automatically bound from the request
    var results = GetSearchResults(query, page);
    return View(results);
}
            

You can also bind to complex objects:

Example: Binding to a Complex Object


public class ProductFilter
{
    public string Category { get; set; }
    public decimal? MinPrice { get; set; }
}

public IActionResult FilterProducts([FromQuery] ProductFilter filter)
{
    // 'filter' object is populated from query string parameters like ?Category=Electronics&MinPrice=100
    var products = GetFilteredProducts(filter);
    return View(products);
}
            

Routing to Controllers

The routing system in ASP.NET Core maps incoming URLs to specific action methods in your controllers. The default convention is ControllerName/ActionName/Id.

URL Pattern Controller Action Method
/Home/Index HomeController Index()
/Products/List ProductsController List()
/Products/Details/5 ProductsController Details(int id) where id is 5

Controller Base vs. Controller

Both ControllerBase and Controller can be used as base classes for controllers.

Conclusion

Controllers are essential components in ASP.NET Core MVC for managing application logic and request handling. By understanding action methods, return types, view data, and model binding, you can effectively build robust and dynamic web applications.

Continue to the next tutorial on Routing to learn how URLs are mapped to your controllers.