Controllers in ASP.NET Core MVC
Controllers are a core component of the Model-View-Controller (MVC) architectural pattern. In ASP.NET Core MVC, controllers are C# classes that handle incoming browser requests, interact with models to retrieve or save data, and select a view to render the response to the client.
What is a Controller?
A controller's primary responsibility is to handle user input and execute the appropriate business logic. It acts as an intermediary between the Model and the View. When a request arrives, the routing mechanism determines which controller and action method should process it.
Creating a Controller
Controllers are typically C# classes that inherit from the Controller base class provided by ASP.NET Core.
using Microsoft.AspNetCore.Mvc;
namespace MyWebApp.Controllers
{
public class HomeController : Controller
{
// Action methods will go here
}
}
By convention, controller classes are named using the pattern ControllerNameController (e.g., HomeController, ProductController). The base Controller class provides access to useful properties and methods, such as:
Request: Represents the incoming HTTP request.
Response: Represents the outgoing HTTP response.
ViewBag: A dynamic property that allows you to pass data from the controller to the view without defining a specific model class.
ViewData: A dictionary that can be used to pass data to the view.
Url: An object for generating URLs to actions.
TempData: A dictionary that allows you to pass data between requests, typically used for redirect scenarios.
Action Methods
Action methods (or simply actions) are public methods within a controller class that handle specific requests. When a request matches a controller and an action name, the corresponding action method is executed.
Action methods must return a type derived from IActionResult. Common return types include:
ViewResult: Renders a view.RedirectResult: Redirects the browser to a different URL.JsonResult: Returns JSON data.ContentResult: Returns plain text content.
Example Action Method
using Microsoft.AspNetCore.Mvc;
namespace MyWebApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
// Return a view named "Index" in the Views/Home folder
return View();
}
public IActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public IActionResult Contact()
{
return View();
}
public IActionResult ShowDetails(int id)
{
// Assuming 'id' is passed from the URL or form
ViewBag.ItemId = id;
return View();
}
public IActionResult RedirectToGoogle()
{
return Redirect("https://www.google.com");
}
public IActionResult GetApiData()
{
var data = new { Name = "Sample Item", Value = 123 };
return Json(data);
}
}
}
In the example above:
Index(),About(), andContact()are action methods that typically return views.ShowDetails(int id)demonstrates how to accept a parameter, which can be bound from the URL or a form.RedirectToGoogle()shows how to perform a client-side redirect.GetApiData()demonstrates returning JSON data, often used for AJAX requests.
Routing to Controllers and Actions
ASP.NET Core uses a flexible routing system to map incoming requests to controller actions. By default, the framework looks for URLs in the format /ControllerName/ActionName/OptionalParameters.
For example:
- A request to
/Home/Indexwill execute theIndexaction in theHomeController. - A request to
/Home/ShowDetails/5will execute theShowDetailsaction in theHomeController, passing5as theidparameter.
You can customize routing extensively using attributes or the configuration in Startup.cs (or Program.cs in .NET 6+).
Convention over Configuration
ASP.NET Core heavily relies on conventions. If you name your controller ProductsController, the framework assumes the corresponding views are in the Views/Products folder. Similarly, if an action method is named List, the framework will look for a view named List.cshtml by default.
Controller Actions that Return Views
When an action method needs to render an HTML page, it typically returns a ViewResult. The View() helper method, available through the base Controller class, is used for this purpose.
Implicit and Explicit View Specification
- Implicit: If you call
return View();without arguments, the framework will look for a view named after the action method (e.g.,Index.cshtmlfor theIndex()action) in a folder named after the controller (e.g.,Views/Home/Index.cshtml). - Explicit: You can specify the view name or path:
return View("About");: Looks forViews/Home/About.cshtml.return View("~/Views/Shared/CustomView.cshtml");: Looks for a view at the specified path.return View("~/Views/Products/Details.cshtml");: Explicitly targets a view in a different controller's folder.
Passing Data to Views
Controllers often need to pass data to views. ASP.NET Core MVC offers several mechanisms for this:
- Strongly-Typed Models: This is the recommended approach. The controller passes an instance of a model class to the
View()method, and the view is strongly typed to that model. ViewBag: A dynamic property that allows you to add properties on the fly. It's convenient for small amounts of data but lacks compile-time checking.ViewData: A dictionary that provides a similar capability toViewBagbut is accessed using string keys.TempData: Used for passing data across requests, often for one-time messages (like "Item saved successfully") after a redirect.
// Controller Action
public IActionResult UserProfile(int userId)
{
var user = _userService.GetUserById(userId); // Assume _userService is injected
// Using strongly-typed model (Recommended)
return View("ProfileView", user);
// Using ViewBag
// ViewBag.UserName = user.Name;
// ViewBag.UserEmail = user.Email;
// return View();
// Using ViewData
// ViewData["UserName"] = user.Name;
// ViewData["UserEmail"] = user.Email;
// return View();
}
API Reference: Controller Base Class
The Microsoft.AspNetCore.Mvc.Controller class provides a rich set of functionalities for building web applications. Key members include:
ControllerContextHttpContextModelStateTempDataProvider- Helper methods like
Ok(),NotFound(),BadRequest(),StatusCode(), etc., for returning specificIActionResulttypes.
For a comprehensive list, refer to the official Microsoft Learn API documentation.