Understanding the basic concepts in MVC C#

What is MVC in C#?

  • The ASP.NET MVC is a Web Application Framework developed by Microsoft.
  • It is an open source implemented using visual studio 2012 and above version.


ASP.NET MVC allows software developers to build a web application as a composition of three roles: Model, View, and Controller.


The MVC model defines web applications with 3 logic layers:

·         Model (business layer)
·         View (display layer)
·         Controller (input control)





(1) The Model interacts with the data source (DB or whatever) and gives you access to your data.

(2) The View interacts with the client, it receives input from somewhere and hands off the data to the Controller it also listens to the Controller to make sure it's displaying the correct data.

(3) The Controller is where all the magic happens; the Controller manipulates data, pushes events, and handles changes in both directions (to/from the View and to/from the Model).

Benefits of ASP.NET MVC:

(1) Makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
(2) Enables full control over the rendered HTML and provides a clean separation of concerns.
(3) Direct control over HTML also means better accessibility for implementing compliance with evolving Web standards.
(4) Facilitates adding more interactivity and responsiveness to existing apps.
(5) Provides better support for test-driven development (TDD).
(6) Works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior.
(7) MVC supports default responsive website and mobile templates.

MVC Application Life Cycle:

As a Dot net developer, We should know how the MVC application runs or works whenever the request is processing from one component to another component. We have more components involved in this request processing pipeline then we know of the controller and the action methods that we work with, that have an equally important role in the request processing. In this section, We are going to discuss the different components which are involved in the MVC application life cycle.


Dotnet Builders
The above figure explains the flow of MVC development Lifecycle.

URLRoutingModule:

 The request is first intercepted by the URL Routing Module which is an HTTP Module. It is this module that decides whether the request would be handled by our MVC application. 
URL Routing Module selects the first matching route.

How does the UrlRoutingModule match the request with the routes in the application?

  • If you look into the RegisterRoutes method called from the global.asax you will notice that we add routes to the routes RouteCollection.
  • This method is called from the application_start event handler of the global.asax It is this RegisterRoutes method which registers all the routes in the application.
  • So now we know that the UrlRoutingModule is aware of all the routes in the application and hence it can match the correct route for the request. The main thing to note here is that the UrlRoutingModule selects the first matching route. As soon as a match is found in the routing table, the scanning process stops.
  • So let’s say we have 10 routes in our application and the more specific route is defined after the more general route so in this case, the specific route that is added later will never be matched since the more general route will always be matched. So we need to take care of this when adding routes to the route collection.
  • Here if the request is matched by any of the routes in route collection then the other routes added later in the collection will not be able to handle the request. Please note that If the request is not matched by any of the routes in the UrlRoutingModule then it is not handled by the MVC Application.



RouteHandler:

  • This MvcRouteHandler object is used to obtain a reference to the MvcHandler object which is the HTTPHandler for our application.                                             
  • When the MvcRouteHandler is created one of the things it does is to call the PostResolveRequestCache() method.

MvcHandler:

Being an Http handler it implements the ProcessRequest() method.
the ProcessRequest() method calls the ProcessRequestInit() method.
In the ProcessRequest() method following happens:
1.    ProcessRequestInit() method is called which creates the ControllerFactory.
2.    This ControllerFactory creates the Controller.
3.    Controller's Execute() method is called.

ControllerFactory:

  • As you can see above one of the things that happen inside the ProcessRequest()  method is that ControllerFactory is obtained that is used to create the Controller object.
  • ControllerFactory implements the interface IControllerFactory. By default, the framework creates the DefaultControllerFactory type when the ControllerFactory is created using the ControllerBuilder.
  • The ControllerBuilder is a singleton class and is used for creating the ControllerFactory. Following line in the ProcessRequestInit() method creates the ControllerFactory.
  • The ControllerBase object is created using the default ControllerFactory implementation. If required we can extend this factory by implementing the IControllerFactory interface and then declaring the following in the Application_Start event in the global.asax.
ControllerBuilder.Current.SetDefaultControllerFactory(typeof(NewFactory))
The SetControllerFactory() method is used to set the custom controller factory instead of the Default Controller Factory that is used by the framework.

Controller:

The controller object uses the ActionInvoker to call the action methods in the controller which we will look into later.
 After the controller object is created using the controller factory following happens :
  1. The Execute() method of the controller base is called
  2. This Execute() method calls the ExecuteCore() method which is declared abstract and is defined by the Controller class.
  3. The Controller class's implementation of the ExecuteCore() method retrieves the action name from the RouteData
  4. ExecuteCore() method calls ActionInvoker's InvokeAction() method.

ActionInvoker:The Action Selector

  • The ActionInvoker class has some of the most important responsibilities of finding the action method in the controller and then invoking the action method.
  • The ActionInvoker class needs to fetch the details of the action method and the controller to execute. These details are provided by the ControlleControllerDescriptor. Descriptor and ActionDescriptor have an important role to play in the ActionInvoker.
  •  ControllerDescriptor is defined as "Encapsulates information that describes a controller, such as its name, type, and actions".
  • ActionDescriptor is defined as "Provides information about an action method, such as its name, controller, parameters, attributes, and filters".
  • One important method of the ActionDescriptor is "FindAction()". This method returns an ActionDescriptor object representing the action to be executed. So ActionInvoker knows which action to call.


 As we have seen above the ActionInvoker's InvokeAction() method is called in the ExecuteCore() method.
 Following happens when the ActionInvoker's InvokeAction() method is called
  1. The ActionInvoker has to get the information about the controller and the action to perform. This information is provided by the descriptor objects. The action and controller descriptor classes provide the name of the controller and the action.
  2. ActionMethod is Invoked.

ActionResult:

  •  This ActionResult is executed and the response is returned back to the client. So ActionResult object represents the result that can be passed across the methods.
  •  Thus it separates the specification from the implementation as it represents the command object. For understanding commands in .NET please refer to the commands.
  •  There are specific ActionResult classes depending on the type of result we want to return like the JSON or Redirection to another method.
  •  The "Controller" class that we use to inherit our controller class's provides many useful features that we can use out of the box.

Following are ActionResult Class:

  1. View Result
  2. JSON Result
  3.  Redirect Result
  4. Content Result

So we have seen till now that the ActionMethod is called by the ActionInvoker

  1. The following happens after the action method is invoked.
  2. The OnActionExecuting methods of the ActionFilters are invoked.
  3.  After this, the action method itself is invoked.
  4.  After the action method is invoked the OnActionExecuted methods of ActionFilters are invoked.
  5. The ActionResult is returned back from the ActionMethod The ExecuteResult() method of the ActionResult is called.

ViewEngine: The Renderer of the View

  • ViewResult is one of the most common return type used in almost all of the applications. It is used to render a view to the client using the ViewEngine. The view engine is responsible for generating the HTML from view.
  • When ViewResult is called by the action invoker it renders the view to the response by overriding the ExecuteResult method.
  • The View engines provided by the framework are the Razor View Engine and Web Form View Engine. But if you need some custom view engine for some custom functionality you can create a new view engine by implementing the IViewEngine interface which all the View Engine’s implement.

The IViewEngine has the following methods:

  1. The FindPartialView method is called when the Controller is looking to return a Partial View with the given Name.
  2. The FindView method is called when the Controller is looking for a View with a given Name.
  3. The release view method is used for releasing the resources held by the ViewEngine.

The following happens after the ExecuteResult() method of ViewResult is called.

  1.  ExecuteResult of ViewResultBase is Invoked
  2.  ViewResultBase calls the FindView of the ViewResult
  3.  ViewResult returns the ViewEngineResult
  4.  The Render() method of the ViewEngineResult is called to Render the view using the ViewEngine.
  5. The response is returned to the client.





Comments

  1. Replies
    1. Would you please explain the coding standards in c#(asp.net)

      Delete
    2. Sure. Keep in touch I will cover C# topic in my future post

      Delete
  2. When will you upload the Coding standards of C#???

    ReplyDelete
    Replies
    1. You can subscribe to this blog so that you can get the notification once I post.

      Delete

Post a Comment

Popular posts from this blog

ASP.Net MVC: ViewData, ViewBag and TempData with examples

Send Mail with Attachment using MVC

Difference Between Web Services, WCF and WEB API