Dot Net For All

ASP.NET MVC Routing Explained with Example

ASP.NET MVC Routing

In my previous article I have discussed about the how to display a collection data and how to edit the dataBut one of the important concept of the ASP.NET MVC is directing of the request to the proper controller. I will ponder over this important concept of asp.net mvc routing with code examples in this article which will make you understand about it. I will also show how we can add default routes to handle the request from client applications.

With the advent of the asp.net mvc we can see that we have clean URL’s need to send a request unlike ASP.NET web forms where URL were suffixed by .aspx extension.

Routing engine is the core part of asp.net and it is not tied to the mvc framework, The routing engine is used to route the request to the controller using the MapRoute api of the RouteCollection class of the System.Web.Routing namespace.

Now if we open and see the RouteConfig.cs file present under the App_Start folder of the project we can see the below code present.

What this code is doing is that it registers this default route to the route collection table which the ASP.NET MVC engine used to redirect the requests.

As seen in the above code, a route named “Default” is registered which takes the URL parameter in the structure as “controller/action/id” and it also provide the default values for all the three parts of the url path with the help of anonymous types for the parameter named defaults.

Suppose if I am browsing to the following URL I will get the results as shown against each example

  1. http://localhost – (Controller – Home, Action – Index) – In this example I am simply browsing to the root location of the website. Since none of the value is provided in the URL all the values for redirect will be taken from default Settings.
  2. http://localhost/Student(Controller – Student, Action – Index) – Since the controller is provided in the URL. The request is redirect to the Student controller and the Index method.
  3. http://localhost/Student/Edit/1 – (Controller – Student, Action – Edit, id -1) –  In this URL all the three parameters are provided that is why the request will just by pass the values from the URL and navigate to the provided values.

The purpose of the following line of code is to by pass the request for the file on the file system as we do not want these request to be processed by the controller instead we just want to pick up these files and send them back to the browser.

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 

Adding A Default Route

In our application if the user directly wants to navigate this URL http://localhost/Student/1 and find the student in the list from the controller.

If we simply enter this URL and send a request we will get a 404 error as from the default structure of the registered route the MVC framework will not be able to find the controller. To circumvent this problem we have to add one more default entry in the routeconfig.cs and the new code will look as shown below.

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

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

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

In the default route configuration of asp.net mvc routing the route is expecting an action but in our case we want the path sent to the action as a parameter. I have defined a new route for this.

We need to be careful where we should add this route. This default route entry(already present) is very common URL path and it will be called on for almost every controller action that we call in the application and will not let go the request through it and it does this because it provides the default parameter for anything  that is missing in the URL. That is why we need to add the new routing configuration before the default route and make that URL a little more restrictive.

I have changed my controller to search for a particular student with the help of Find Method and added a corresponding view for that

        public ActionResult Find(int id)
        {
            var editedStudent = studentList.Where(item => item.StudentID == id).First();
            return View(editedStudent);
        }

and now if I send a request using the URL I will get a UI as shown in the below figure

More over if we want to get the routing information for the request by which some particular action has been executed we can always use the following code in the action method.

            var controller = RouteData.Values["controller"];
            var action = RouteData.Values["action"];
            var id = RouteData.Values["id"];

Here is a very interesting article about how routing works internally.

Conclusion:

In this article I have shown I asp.net mvc routing works and how we can add more default routed to the application and how we can get the routing in the controller.

 

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview