Controllers in MVC

In ASP.NET Core MVC, controllers are responsible for handling incoming HTTP requests and determining how the application responds. They act as the central coordination point between the user interface (views) and the application's business logic.

Whenever a user interacts with your application—such as clicking a link, submitting a form, or accessing a URL—the request is routed to a controller. The controller processes that request, interacts with data if needed, and returns an appropriate response.

Understanding how controllers work is fundamental to building scalable and maintainable ASP.NET Core MVC applications.


What Is a Controller in ASP.NET Core MVC?

A controller is a class that inherits from the Controller base class and is responsible for handling user requests.

It contains methods called action methods, which are executed when a matching request is received.

Controllers are designed to:

  • Receive HTTP requests from the client
  • Process input data
  • Interact with models or services
  • Return responses such as views, JSON, or files

In simple terms, controllers decide what should happen when a user makes a request.


Role of Controllers in MVC Architecture

In the MVC (Model-View-Controller) pattern, controllers act as the mediator between the model and the view.

They do not directly handle UI rendering or database operations. Instead, they coordinate these components.

  • Model – Represents data and business logic
  • View – Displays data to the user
  • Controller – Handles requests and controls application flow

This separation of concerns helps keep the application clean, maintainable, and easy to scale.


Basic Example of a Controller

Below is a simple example of a controller in ASP.NET Core MVC:


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

This example demonstrates a basic controller that returns a view.

Let’s break it down:

  • HomeController is the controller name
  • It inherits from the Controller class, which provides built-in functionality
  • Index() is an action method that handles requests
  • View() returns a Razor view to the browser

When a user visits /Home/Index, this method is executed and the corresponding view is rendered.


Controller Naming Convention

ASP.NET Core MVC uses naming conventions to identify controllers automatically.

  • Controller class names must end with Controller
  • Example: HomeController, ProductController

This convention allows the routing system to map URLs to the correct controller without additional configuration.

Failing to follow this convention may result in routing issues.


How Routing Connects to Controllers

Routing is responsible for mapping incoming URLs to specific controller actions.

Consider the default route:

/Home/Index

This is interpreted as:

  • Home → Controller (HomeController)
  • Index → Action method

The routing system automatically locates the controller and executes the matching action method.

This mechanism allows clean and user-friendly URLs.


Returning Different Types of Results

Controllers are not limited to returning views. They can return different types of responses depending on the application requirements.

  • View() – Returns an HTML page
  • Json() – Returns JSON data
  • File() – Returns files such as PDFs or images
  • Redirect() – Redirects to another URL

Example of returning JSON data:


public IActionResult GetUser()
{
    return Json(new { name = "John" });
}

This is commonly used in APIs and dynamic web applications.


Multiple Action Methods in a Controller

A single controller can handle multiple requests using different action methods.


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

    public IActionResult About()
    {
        return View();
    }
}

Each action method corresponds to a different route and view.

This allows logical grouping of related functionality within a single controller.


Passing Data from Controller to View

Controllers often need to pass data to views for rendering.

This can be done using ViewBag, ViewData, or strongly typed models.

Example using ViewBag:


public IActionResult Index()
{
    ViewBag.Message = "Welcome to ASP.NET Core MVC";
    return View();
}

The view can access this data and display it to the user.

In real-world applications, strongly typed models are preferred for better maintainability.


Real-World Example: Using Controller with Data

In real-world applications, controllers are often used to fetch data and pass it to views for display.

Let’s consider a simple example where a controller sends product data to a view.


public class ProductController : Controller
{
    public IActionResult List()
    {
        var products = new[] 
        {
            new { Id = 1, Name = "Laptop" },
            new { Id = 2, Name = "Mobile" }
        };

        return View(products);
    }
}

In this example:

  • The ProductController handles product-related requests
  • The List() action method creates a list of products
  • The data is passed to the view using View(products)

When the user navigates to /Product/List, the controller executes this method and sends the product data to the view.

The view can then display this data in a table or list format.

This pattern is commonly used in real-world applications such as e-commerce websites, dashboards, and admin panels.

It demonstrates how controllers manage data and connect business logic with the user interface.


Best Practices for Controllers

To build scalable applications, controllers should follow certain best practices:

  • Keep controllers lightweight and focused
  • Avoid placing business logic inside controllers
  • Use services or repositories for data operations
  • Follow naming conventions consistently
  • Return appropriate result types

These practices help maintain clean architecture and improve testability.


Common Mistakes to Avoid

  • Writing too much logic inside controllers
  • Ignoring separation of concerns
  • Not understanding routing behavior
  • Returning incorrect response types

Avoiding these mistakes will help you write professional and maintainable code.


Summary

Controllers are a core component of ASP.NET Core MVC that handle user requests and control the flow of the application.

They act as the bridge between models and views, ensuring that data is processed and displayed correctly.

By understanding controllers, routing, and action methods, you can build structured, scalable, and maintainable web applications.

In the next lesson, you will learn how to create controllers and define action methods in detail.