Before writing anything about MVC we must understand what MVC is and what Routing is in MVC. This article describe how routing is working in MVC.
MVC stands for Modal View Controller.
As per my understanding the fact behind the MVC is shown in above image.
MVC Routing Engine:
Routing
Routing is a very complex topic in MVC. So more we make our hands dirty on routing more we can play easily in MVC. Routing is responsible to map the incoming request with the appropriate controller. And to call that routing is the start point in MVC.
Look at the image below:
Its showing routing data gets filled up in App_start event that exists in Global.asax file. The important method is “RegisterRoutes”.
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new
- {
- controller = "Home", action = "Index", id = UrlParameter.Optional
- });
- }
The above method is responsible to map the route. Let’s get into the details of this method line by line.
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
This represents clear instruction for the incoming request, Please ignore anything which ends with .axd and having any other additional parameter.
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
- );
This actually defines the default route. Any incoming request first hit the Controller then method with defined parameter
("{controller}/{action}/{id}",). In the next line it is defined the default constructor is “
Home” and method to be called is “
Index”. The “
id” parameter is optional as we can have method without any parameter.
How to customize Routes Now in case user want to access ”
IAmThereController” (as defined in code), then our default route will work for the same.
Let us see how I have defined new controller, here's the code:
- public class IAMThereController: Controller
- {
-
-
- public string Index()
- {
- return "This is default Method";
- }
- public ActionResult Welcome(string name)
- {
- ViewBag.a = "welcome " + name;
- return View();
- }
- }
- Request: http://localhost:61833/Iamthere
Output:
- The second request is very interesting,
Request: http://localhost:61833/iamthere/welcome/nishant
Output: It will not print “Welcome Nishant”, check below. I have debugged the same and found name is coming as null. Look at below:
And it will not print “Welcome Nishant”
To fix this error: We need to define a new Route that tells the routing handler how to navigate to an action method with name parameter. I have changed my route:
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{name}",
- defaults: new
- {
- controller = "Home",
- action = "Index",
- name= UrlParameter.Optional
- }
- );
Hope this will help to understand the basic concept of Routing.