Wednesday, 25 September 2013

Routing In MVC

Routing In MVC:
ASP.Net Routing is setup in two places:

1.       In Web.config file. There are 4 sections in configuration file that are relevant to routing configuration:
         System.web.httpModules
         System.web.httpHandlers
         System.webserver.modules
         System.webserver.handlers

2.       In Global.asax, is a specific file that contains event handlers for ASP.Net application lifecycle events. The Route table is created during the Application_Start event as follows:

Protected void Application_Start()
{
                RegisterRoutes(RouteTable.Routes);
}

When an MVC application starts, the Application_Start() method is called. This in turn calls the RegisterRoutes() method, this method creates the route table.

The default route table contains a single route named as Default. The Default route maps the first segment of URL to controller, second to controller action, third to parameters.

Consider user enters the URL: …/Home/Index/8

Controller = Home
Action = Index

Parameters = 8

MVC Execution Flow

MVC Execution Flow:

Browser à Global.asax à URL Routing à Controller à Controller Invokes action à Returns Action Result à Returns to View Rendered HTML content à Response back to browser.

     1.       When user enters URL in Browser. Consider URL:  ABC.com/home/index
     
     2.       In Global.asax, the specific entered URL will be parsed through application_start() method of it.                     From the requested URL, it will parse Controller, Action and Parameters.

           ABC.com/home/index:
           Controller = home
           Action=index
           Parameters= empty – No parameters passed here in above URL
  
    3.       Now finds the home controller in controllers directory which contains several action methods, in that it           will invoke the index action method 

   4.       It will render HTML and returns to View.


What is MVC ?

MVC

MVC stands for Model View and Controller, which requires Microsoft .Net Framework 3.5 and higher.

Model:
It is basically is a C# or VB.Net class used for interaction between Controller and View.

View:
It is an ASPX page without having code behind file.
A request to View can be made only through the Controller.

Controller:

Controller is a heart of the entire MVC architecture, in which action methods are implemented which are responsible for responding to browser and calling Views.