Controllers & Actions in ASP.NET Core

Actions are methods that handle HTTP requests. Controllers group related actions.

60-Second Version: Controller = Department Manager. Action = Specific task. ProductController manages products. Index() lists all, Details(int id) shows one.

1. Anatomy of an Action

public class ProductController : Controller
{
    // GET: /Product/Details/5
    public IActionResult Details(int id)
    {
        var product = _db.Products.Find(id); // Get data
        if (product == null) return NotFound(); // 404
        return View(product); // 200 + HTML
    }
}

3 Parts: 1. Route matches โ†’ 2. Method runs โ†’ 3. IActionResult returned.

2. Common IActionResult Types

ReturnHTTP CodeUse For
View()200Return Razor page
Json(data)200API endpoint
RedirectToAction("Index")302After POST save
NotFound()404Id doesn't exist
BadRequest()400Invalid input

3. Parameters: How Data Gets Into Actions

URL: /product/details/5?sort=name

public IActionResult Details(int id, string sort)
{
    // id = 5 from route: {controller}/{action}/{id}
    // sort = "name" from query string?sort=name
}

Rule: Route values โ†’ Query string โ†’ Form data. ASP.NET auto-binds if names match.

4. GET vs POST: The Golden Rule

[HttpGet] // Show the form
public IActionResult Create()
{
    return View();
}

[HttpPost] // Handle form submit
public IActionResult Create(Product product)
{
    if (!ModelState.IsValid) return View(product); // Show errors
    _db.Products.Add(product);
    _db.SaveChanges();
    return RedirectToAction("Index"); // PRG Pattern
}
PRG Pattern: Post-Redirect-Get. Prevents duplicate form submit on refresh.
Beginner Trap: Sanju writes public void Delete(int id). Browser gets blank page. Fix: Always return IActionResult. Void = no HTTP response.

Quick Check ๐Ÿง 

Next: Routing in MVC - Conventional vs Attribute routing, constraints, and URL generation.

Comments on Controllers & Actions (0)

No comments yet. Be the first to share your thoughts!