In ASP.NET Core MVC, a controller is a class that handles incoming HTTP requests, processes user input, interacts with a model, and selects a view to render the response.
using Microsoft.AspNetCore.Mvc;
namespace MyApp.Controllers
{
public class HomeController : Controller
{
// Action method for the Home page
public IActionResult Index()
{
return View();
}
// Action method that receives a route parameter
public IActionResult Details(int id)
{
var model = GetItemById(id);
return View(model);
}
}
}
An action method is a public method on a controller that can be invoked via a URL. By default, action methods return an IActionResult which can be a view, JSON, redirect, etc.
[HttpPost]
public IActionResult Create(Product model)
{
if (ModelState.IsValid)
{
_repository.Add(model);
return RedirectToAction(nameof(Index));
}
return View(model);
}
The default routing pattern maps URLs to controller actions in the form /[controller]/[action]/{id?}. You can customize routes with attributes.
[Route("products/{id:int}")]
public IActionResult Details(int id) { /* ... */ }
[HttpGet("search")]
public IActionResult Search(string term) { /* ... */ }
Enter a product ID to see how the Details action would be called.