MVC Framework - Controllers MVC Controllers are responsible for controlling the flow of the application execution. When you make a request (means request a page) to MVC application, a controller is responsible for returning the response to that request. The controller can perform one or more actions. The controller action can return different types of action results to a particular request.

The Controller is responsible for controlling the application logic and acts as the coordinator between the View and the Model. The Controller receives an input from the users via the View, then processes the user's data with the help of Model and passes the results back to the View.

Create a Controller

To create a Controller −

Step 1 − Create an MVC Empty Application and then right-click on the Controller folder in your MVC application.

Step 2 − Select the menu option Add → Controller. After selection, the Add Controller dialog is displayed. Name the Controller as DemoController.

A Controller class file will be created as shown in the following screenshot.

MVC New Controller

Create a Controller with IController

In the MVC Framework, controller classes must implement the IController interface from the System.Web.Mvc namespace.

public interface IController {
   void Execute(RequestContext requestContext);

This is a very simple interface. The sole method, Execute, is invoked when a request is targeted at the controller class. The MVC Framework knows which controller class has been targeted in a request by reading the value of the controller property generated by the routing data.

Add New Controller Class

Step 1 − Add a new class file and name it as DemoCustomController. Now modify this class to inherit IController interface.

Controller Using IController

Step 2 − Copy the following code inside this class.

public class DemoCustomController:IController { 
   public void Execute(System.Web.Routing.RequestContext requestContext) { 
      var controller = (string)requestContext.RouteData.Values["controller"]; 
      var action = (string)requestContext.RouteData.Values["action"]; 
      string.Format("Controller: {0}, Action: {1}", controller, action)); 

Step 3 − Run the application and you will receive the following output.

Call Demo Controller