Your comprehensive guide to mastering 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.
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.
Let's create a basic controller named HomeController:
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 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 methods can return various types of results:
ViewResult: Renders an HTML view.ContentResult: Returns plain text or HTML content.JsonResult: Returns data in JSON format.RedirectResult: Redirects the user to a different URL.FileResult: Returns a file to the browser.IActionResult.Controllers use ViewData and ViewBag to pass data to views.
ViewData: A dictionary used to pass data between the controller and the view. It requires explicit casting in the view.ViewBag: A dynamic property that provides a more convenient way to pass data. It's essentially a wrapper around ViewData.
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
}
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.
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:
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);
}
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 |
Both ControllerBase and Controller can be used as base classes for controllers.
ControllerBase: Provides the core functionality for controllers, suitable for API controllers or when you don't need view rendering capabilities.Controller: Inherits from ControllerBase and adds support for view rendering, view data, view bags, and other view-related features. Use this for traditional MVC applications.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.