In ASP.NET MVC, the Controller is responsible for handling user input, interacting with the model, and returning a response. Controllers define actions, which correspond to individual endpoints accessible via a web request.
A Controller in ASP.NET MVC is a class that handles HTTP requests. It is part of the MVC (Model-View-Controller) design pattern and is responsible for processing incoming requests, performing business logic, and returning responses.
Controllers are created by inheriting from the Controller base class. Below is an example of a basic controller:
Controller
using Microsoft.AspNetCore.Mvc; public class HomeController : Controller { public IActionResult Index() { return View(); } }
Actions are methods inside a controller that handle HTTP requests. Each action method returns an IActionResult, which represents the response.
IActionResult
Action methods in a controller typically return a view or JSON response. Here’s an example:
public class HomeController : Controller { public IActionResult Index() { return View(); // Returns a view named "Index" } public IActionResult About() { return Content("This is the About page."); } }
By default, ASP.NET MVC uses conventional routing to determine which action method to call based on the URL pattern. Attribute routing can also be used for more control.
using Microsoft.AspNetCore.Mvc; [Route("api/[controller]")] public class ProductsController : Controller { [HttpGet("all")] public IActionResult GetAllProducts() { return Ok(new string[] { "Product1", "Product2" }); } }
Action methods can return different types of results, such as:
ViewResult
JsonResult
ContentResult
RedirectResult
public IActionResult Details() { return Json(new { Name = "Laptop", Price = 1200 }); }
Controllers and Actions are the core building blocks of ASP.NET MVC. Controllers handle user requests, perform logic, and return appropriate responses through action methods.
Comments - Beta - WIP