Controllers in ASP.NET Core MVC

Controllers are the heart of an ASP.NET Core MVC application. They handle incoming browser requests, interact with models to retrieve or save data, and select views to render responses. This tutorial will guide you through understanding and working with controllers.

What is a Controller?

A controller is a class that typically inherits from Controller base class provided by ASP.NET Core. It contains public methods called action methods, which are executed in response to specific HTTP requests.

Creating a Controller

You can create a new controller by adding a new class to your project in the Controllers folder. Let's create a simple HomeController.

Example: HomeController.cs

public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public IActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } }

Action Methods

Action methods are public methods within a controller that return an IActionResult. This interface represents the result of an action method, such as rendering a view, returning JSON data, or performing a redirection.

Key aspects of Action Methods:

Common IActionResult types:

Note: The Controller base class provides helpful methods for returning various IActionResult types, like View(), Json(), and RedirectToAction().

Routing to Controllers

ASP.NET Core uses a routing system to map incoming URLs to specific action methods. By default, the route pattern is typically /[Controller]/[Action]/[Parameters].

For example, the URL /Home/About would typically invoke the About action method in the HomeController.

Want to see how routing works? Try changing the URL in your browser's address bar to /Home/About or /Home/Contact.

Passing Data to Views

Controllers often need to pass data to the views for display. ASP.NET Core provides several mechanisms for this:

Example: Passing data using ViewBag

In the About() action method above, we used ViewBag.Message to pass a string to the view. In the corresponding view (e.g., Views/Home/About.cshtml), you would access it like this:

@{ ViewData["Title"] = "About Us"; }

@ViewData["Title"]

@ViewBag.Message

Use this area to provide more information about your application.

Controller Naming Conventions

Controller classes typically end with the suffix Controller (e.g., HomeController, ProductsController). When routing, the Controller suffix is usually omitted. So, HomeController matches the Home part of the route.

Conclusion

Controllers are fundamental to building MVC applications in ASP.NET Core. By understanding how to create controllers, define action methods, and pass data to views, you lay the groundwork for creating dynamic and interactive web applications.