Back
Controllers and Actions in ASP.NET MVC

Controllers and Actions in ASP.NET MVC

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.

What is a Controller?

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.

Creating a Controller

Controllers are created by inheriting from the Controller base class. Below is an example of a basic controller:

using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

Understanding Actions

Actions are methods inside a controller that handle HTTP requests. Each action method returns an IActionResult, which represents the response.

Defining Action Methods

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.");
    }
}

Routing in Controllers

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" });
    }
}

Returning Different Action Results

Action methods can return different types of results, such as:

  • ViewResult - Returns a View.
  • JsonResult - Returns JSON data.
  • ContentResult - Returns plain text.
  • RedirectResult - Redirects to another action or URL.
public IActionResult Details()
{
    return Json(new { Name = "Laptop", Price = 1200 });
}

Conclusion

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

Leave a Comment