Page Life Cycle in ASP.Net MVC


Model–view–controller (MVC) is a software architectural pattern, It divides a given software application into three interconnected parts i.e. Model, View & Controller.
1. The Model manages fundamental behaviors and data of the application.
2. The view provides the user interface element of the application and renders data from the model.
3. The Controllers act as an interface between Model and View, it receives user input and makes calls to model objects and the view to perform appropriate actions

Asp.net MVC page life cycle is different from the traditional ASP.net, there are no events like pre render, oninit etc., which we have in web forms. 

When we look from high level it looks like; we request a URL, some controller action is called and response is rendered in browser. But between this request and rendering, following are the main steps involved in asp.net MVC page life cycle:

Here I am trying to explain this steps in short:-
  • Once IIS determines request need to processed by ASP.Net, UrlRoutingModule get change to act on request as any standard HTTP module
  • UrlRoutingModule checks if the request path matches the route configured with the application (Routing explained in detail at end)
  • UrlRoutingModule gets the IHttpHandler from the corresponding route's IRouteHandler
    • MvcRouteHandler is the default route handler for MVC application
  • In response to GetHttpHandler, MvcRouteHandler returns MvcHandler which implements IHttpHandler.
    • The MvcHandler is responsible for initiating the real processing inside ASP.Net MVC. The handler returned from the RouteTable will always be an MvcHandler. This MVCHandler also derive from interface IHTTPHandler and implement the method ProcessRequest().
  • IRouteHandler executes ProcessRequest method of McvHandler passing current HttpContext. MvcHandler uses IControllerFactory to obtain an instance of IController using controller name in the request path.
    • When the ProcessRequest method is called a new controller instance gets created by ControllerFactory. DefaultControllerFactory is default IControllerFactory in ASP.Net MVC, you can create your own also.
  • Once the controller has been instantiated, MVC handler invokes Executes method on the controller. OnActionExecuted and OnResultExecuting methods of action filters also get invoked
  • Controller executes the method corresponding to Action specified in path.
    • Action to be execute is chosen based on attributes ActionNameSelectorAttribute (by default method which have the same name as the action is chosen) and ActionMethodSelectorAttribute(If more than one method found, the correct one is chosen with the help of this attribute).
  • The action method receives user input, prepares the appropriate response data, add data to ViewData directory if needed, and then executes the result by returning a result type.
    • The result type can be ViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.
  • ExecuteResult method of ActionResult is executed passing the ControllerContext.
  • ViewResult locates the corresponding view using configured view engine.
    • WebFormViewEngine is default one.
  • ViewResult invokes render method on View.
    • The first step in the execution of the View Result involves the selection of the appropriate View Engine to render the View Result. It is handled by IViewEngine interface of the view engine. By default Asp.Net MVC uses WebForm and Razor view engines. You can also register your own custom view engine to your Asp.Net MVC application as follows,

            protected void Application_Start()
            {
                //Remove All View Engine including Webform and Razor
                ViewEngines.Engines.Clear();
                //Register Your Custom View Engine
                ViewEngines.Engines.Add(new CustomViewEngine());
                //Other code is removed for clarity
            }

 
Routing in Detail:-Asp.net Routing is the first step in MVC request cycle. Basically it is a pattern matching system that matches the request's URL against the registered URL patterns in the Route Table. When a matching pattern found in the Route Table, the Routing engine forwards the request to the corresponding IRouteHandler for that request.
When application starts at first time, Application_Start events will get called and it will call the method RegisterRoutes, it registers one or more patterns to the Route Table to tell the routing system what to do with any requests that match these patterns. An application has only one Route Table and this is setup in the Global.asax file of the application.

        protected void Application_Start()
        {
            RouteConfig.RegisterRoutes(RouteTable.Routes);
                  ………..
               ………..
        }

And in RouteConfig.cs file we define the routing/mapping details as,

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Common", action = "Default", id = UrlParameter.Optional }
            );
        }

Here, In MapRoute we will define the Name, Url, and Default page for application.



(NOTE: - In ASP.NET application each asp.net page implements the IHTTPHandler interface. This interface has a ProcessRequest() method that gets called when you request the page, which is responsible for processing the request and generating the response. So in asp.net application it is simple, you request for a page in the url like http://SiuteName\default.aspx and then it search for that page on the disk and execute the ProcessRequest method and generate the response.

However in MVC application it doesn't work in that way. There is no physical page exist for a particular request. All the requests are routed to a special class called Controller. The controller is responsible for generating the response and sending the content back to the browser.)

 

Comments

  1. "Great blog created by you. I read your blog, its best and useful information. You have done a great work. Super blogging and keep it up.php jobs in hyderabad.
    "

    ReplyDelete

Post a Comment