English 中文(简体)
MVC Framework - Controllers
  • 时间:2024-12-22

MVC Framework - Controllers


Previous Page Next Page  

Asp.net MVC Controllers are responsible for controlpng the flow of the apppcation execution. When you make a request (means request a page) to MVC apppcation, 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 controlpng the apppcation 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 Apppcation and then right-cpck on the Controller folder in your MVC apppcation.

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.

pubpc 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.

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

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

Call Demo Controller Advertisements