5. Controllers and Actions
A controller is a class that ends with the word Controller and inherits from Controller. Each public method is an action that can respond to a request. An action returns an IActionResult, such as a view, a redirect, or a status code. Keep controllers thin: they coordinate, they do not hold business logic.
Key points
- View() returns the matching Razor view.
- RedirectToAction() sends the browser to another action.
- NotFound(), BadRequest() and Ok() return HTTP status codes.
- Return Json() when you need data instead of a page.
Example: A basic controller
public class StudentsController : Controller
{
public IActionResult Index()
{
var students = new List<Student>
{
new Student { Id = 1, Name = "Ana", Age = 20 },
new Student { Id = 2, Name = "Sipho", Age = 22 }
};
return View(students); // sends the list to Views/Students/Index.cshtml
}
public IActionResult Details(int id)
{
if (id <= 0) return NotFound();
return View();
}
}
Show explanation
Index runs for /Students and passes a list to its view. Details runs for /Students/Details/5 and returns a 404 page when the id is invalid.