Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Controller in MVC

0.00/5 (No votes)
30 Dec 2014 1  
Controller is one of the most important component in an MVC application since it acts as a coordinator between the view and the model and also handles the users requests.The user's request is received by the controller.The post Controller in MVC appeared first on codecompiled.com

Controller is one of the most important component in an MVC application since it acts as a coordinator between the view and the model and also handles the users requests.The user’s request is received by the controller which requests the model to perform different CRUD operations ,based on the request, and then decides the result to return to the user.

In the case of web forms there is a direct relationship between the URL and a file on the server’s hard drive as the requested file is requested by the user and is part of the URL.

In MVC there is a decoupled relationship between the requested URL and the controller class used to serve the request.The client just makes a request using a URL and it’s the responsibility of the MVC application to pass the request to the appropriate component or the controller which will handle the request.

This decoupling makes changing the URL structure easy as the user is not aware of the file which actually serves the request.This is also good from the encapsulation point as the internal details of the application are not exposed to the outside world.

The mapping between the URL and the controller class,which will handle the request, is the responsibility of the URLRouting module which is an HTTPModule.

controller in mvc

WebForms page is executed when requested by the browser

controller in mvc

The routing module in mvc decouples the controller from the request

From the URLRoutingModule the request is passed to the Controller which contains the action methods which actually handles the request.Once the request reaches the controller ,it decides the model on which to perform the operation and then decides the result which needs to be returned to the client.

Usually we have a controller class for every major feature our application provides.

So controller is where we write the code to serve the requests.Following are some of the important characteristics of controllers.

1.Controller classes and Interface Framework requires that all controller classes inherit from the IController interface .The IController interface specifies a single method called Execute() which receives a RequestContext object.

MVC makes it easier for us to implement controller by providing a base class called Controller which implements the IController interface.So we can inherit from the Controller class instead of writing all the boilerplate code required to implement the IController interface.ControllerBase is the parent class of Controller class and implements the basic controller functionality. ControllerBase also implements the IController’s Execute() method.

controller in mvc

Our Controller class derives from the base Controller class

We derive our controller class,which contains the application logic, from the Controller class which derives from the ControllerBase class.Both the Controller class and the ControllerBase class implements functionality which is required by our controller class.

ControllerBase implements the IController interface ,which is required to be implemented by all controllers in MVC.Also it defines a few important properties that we can access from the action method such as

  • ViewData To pass the data to the view using a dictionary object
  • ViewBag To pass the data to the view using dynamic property
  • TempData To pass the data across the controllers

Controller class inherits the above properties from the ControllerBase class and also provides its own useful properties such as

Property Use
Request References the Current HTTP request.
Response References the Current HTTP response
Server Contains useful methods for the request handling
Session References the current Session.
ActionInvoker References the ActionInvoker for the Controller

2. Action Methods Controller classes that we define by inheriting from the Controller class expects us to define the application logic in different action methods.Each action method corresponds to a URL and is invoked when the URL is requested by the client.

controller to route mapping

Different URL’s are handled by the different Action Methods of a Controller class

The action method to execute is selected by the ActionInvoker component of MVC.It implements the IActionInvoker interface. The default ActionInvoker provided by the framework selects the action method by the action method name.

3. Filters for implementing the Cross cutting concerns Cross-cutting concern refers to the functionality which is supposed to be used in many different parts of the application.If we take the example of logging then different parts of the application may need access to the logging functionality.To cleanly implement the cross cutting concerns we must reuse the common functionality instead of redefining the same functionality in different places.

Cross cutting concerns are implemented in MVC by using filter attributes.Instead of duplicating the common functionality in different controllers and action methods ,filters define the common functionality.So we can easily apply the cross cutting concerns by decorating the action methods and controllers with attributes.These attributes in-turn invokes the attribute class.

Commonly used filter attributes are

Filter Use
Authentication This specifies the authentication logic.User is allowed to access the action method only if he is authenticated.
Authorization This specifies the authorization logic.User is allowed to access the action method only if he is authorized.
Action Executed before and after the action method has executed
Result Executed before and after the ActionResult has executed
Exception Executed when the action throws an unhandled exception

4. Action methods returns the ActionResults Instead of returning the result to the user ,action method instead returns the ActionResult which specifies the result that has to be returned to the user.Action Result returned by the action method is an object of a class deriving from ActionResult class.This is an example of a command pattern which encapsulates the operation so that it can be passed to other methods in the application.This decouples the object that is handling the responsibility of per froming an action from the object which wants to perform the action.So the responsibility of the action method is just to return the ActionResult ,it is executed later in the request pipeline.

As the ActionResult is an abstract class ,framework provides different ActionResult derived classes for returning different types of results from the action method.There are different ActionResult types such as ViewResult,RedirectResult,JsonResult .

The action method can directly create and return the ActionResult instance as

public ActionResult Create()
{
ViewResult result = new ViewResult();
return result;
}

But instead of creating the ViewResult instance directly in the action method we can use the helper methods provided by the Controller class from which our controller classes derives.So to return the ViewResult we can use the helper method as

public ActionResult Create()
{
return View();
}

Some of the ActionResults and the corresponding helper methods used to generate the ActionResults are

ActionResult type Use Helper method
ViewResult Renders a view View()
PartialViewResult Renders a partial view ,which is a view that is part of another view PartialView()
RedirectResult Redirects to another action method Redirect()
ContentResult Returns the specified content type Content()
JsonResult Returns a JSON object. Json()

So as we have seen Controllers in MVC are responsible for handling the application logic.We can use the framework provided controller classes or if we need fine grained control we can create and plugin a new controller class by directly implementing the IController interface.

The post Controller in MVC appeared first on codecompiled.com.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here