Routing In ASP.NET MVC 5.0 - Part Nineteen

Before reading this article, I highly recommend reading the previous parts of the series on ASP.NET:

Routing

Routing is a pattern matching system that enables you to map incoming browser requests to a particular MVC action defined in the controller. Routing engine uses the route table for matching the incoming request’s URL patterns against the URL patterns defined in the route table. RouteConfig file is used for adding the routing rules. Routing is a way to call the controllers and their actions.

We register routes in the Global.asax file and we invoke a RegisterRoutes method in the Application_Start() method. Routing is used to create user friendly URLs. It can also be used to setup the startup page of the application, just like the ASP.NET Web Forms. The routing system enables us to create any pattern of URLs you desire and express them in a clear and concise manner.

Here is the Routing Engine to perform the routing. A URL is passed on the request of the user and the system locates the matching route. After that, if URL is found, then it is processed otherwise it throws an error. When the ASP.NET Routing Engine receives a request at run time, then it finds a match for that requested URL with the URL pattern defined in the route table. If there is any match found, then it forwards the request to the appropriate controller, otherwise it returns HTTP 404 error.

error

Here, you can see the URL pattern. The chapters would be controller and action which would be speakers and would be optional, this request matches the request Home/Action where Action is the method of Home controller. But in the routing rule you can add more pieces of request that is an optional id parameter, because we might need to use some information in a URL to identify a particular record. That’s why routing engine knows the parameter is optional.
url

So, how to add routes in MVC map controllers to the action. Let's go for it. Follow the steps.

Step 1: Open Visual Studio 2013.
Step 2: Under Installed > Templates > Visual C#.
Step 3: In the application list panel, select Asp.Net Web application.
Step 4: Give a name to your project, here I given it “RoutingInMVC”.
Step 5: Hit on to “Ok” button (Follow steps in sequence).

web app

In the below figure, as you can see the default MVC will be selected, select MVC and then click “OK” button.

mvc

So, your project would be created as per your expectations. In every MVC application there is a RouteConfig file in the App_Start folder and that file is responsible for overall routing. When you create a new ASP.NET MVC application, the application is already configured to use ASP.NET Routing.

The Default Route

The default routes are generated when you create a new MVC project. The RouteConfig class has a single method called RegisterRoutes;  this class called when our application is started and this static class is starting from Global.asax file. After that you call IgnoreRoute because of any request with .axd -- in this you can be sure certain resources and system utilities will be handled by the separate handler. The (*) sign before the pathinfo means that you want to treat the last segment in the url pattern as a catch-all that will want to match a single token after. So we can say IgnoreRoutes are used to prevent specific routes like web.config, image file etc.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7.   
  8. namespace RoutingInMVC  
  9. {  
  10.     public class RouteConfig  
  11.     {  
  12.         public static void RegisterRoutes(RouteCollection routes)  
  13.         {  
  14.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  15. }  
  16. }  
  17. }  
MapRout() method is an extension method which means this method is already defined into the route collection. Now we have to define the route name which is default; if you want to create a new route then I have given another name because the name can’t be the same. Next in the URL there are some segnment variables like controller, action and id. Finally in the defaults this will call a specific controller, action and id.
  1. routes.MapRoute(  
  2.              name: "Default",  
  3.              url: "{controller}/{action}/{id}",  
  4.              defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
  5.          );  
  6.      }  
  7.  }  
code

The Route table is created in the Global.asax file, this file handles all application and session regarding events. The route table is created during the Application _Start() event, when application starts the Application_Start() method is called. The entry point of any application is Application_Start().
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Optimization;  
  7. using System.Web.Routing;  
  8.   
  9. namespace RoutingInMVC  
  10. {  
  11.     public class MvcApplication : System.Web.HttpApplication  
  12.     {  
  13.         protected void Application_Start()  
  14.         {  
  15.             AreaRegistration.RegisterAllAreas();  
  16.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  17.             RouteConfig.RegisterRoutes(RouteTable.Routes);  
  18.             BundleConfig.RegisterBundles(BundleTable.Bundles);  
  19.         }  
  20.     }  
  21. }  
code

Creating Custom Routes

First creating a controller Author name where I can show all the operations regarding the routes, right click on to Controllers folder and add a new one.

add

Give a proper name to your controller.

controller

Now controller is created, and by making some changes over there I have an action method named AuthorDetail which contains a parameter id that is integer type and named for the author. Here I am using ViewBag to pass the data from controller to the corresponding view.

code

Add a view for this Action method, by right clicking near Action method.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace RoutingInMVC.Controllers  
  8. {  
  9.     public class AuthorController : Controller  
  10.     {  
  11.         // GET: Author  
  12.   
  13.   
  14.         public ActionResult AuthorDetail( string id, string AuthorName)  
  15.         {  
  16.             ViewBag.authorId = id;  
  17.             ViewBag.authorName = AuthorName;  
  18.             return View();  
  19.         }  
  20.     }  
  21. }  
code

It takes a default name AuthorDetail for the View, click on the add button.

AuthorDetail

Call the respective parameter for Id and Name by using Razor syntax.
  1. @{  
  2.     ViewBag.Title = "AuthorDetail";  
  3. }  
  4.   
  5. <h2>AuthorDetail</h2>  
Author ID: @ViewBag.authorId<br /><br/>
Auhtor Name: @ViewBag.authorName

code

Open the RouteConfig file and create a new route name --  Author in the RouteConfig class by calling the MapRoute method using the object of RouteCollection class (see the screenshot). Where controller is “Author” and action is “AuthorDetail”.
  1. routes.MapRoute(  
  2.                 name: "Author",  
  3.                 url: "{Author}/{AuthorID}",  
  4.                 defaults: new  
  5.                 {  
  6.                     controller = "Author",  
  7.                     action = "AuthorDetail"  
  8.                       
  9.                 }  
  10.             );  
code

Let’s run the application. URL will be something like this.

http://localhost:14868/Author/AuthorDetail

Here, you are calling “AuthorDetail” View, which is showing Id and Name.

AuthorDetail

Now, pass an id of integer type in the Url, hence result will happen and Url as well.

Url

Now, pass the name of author, like query string, look at the URL and result.

Url

Defining Route attribute on controller action method,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace RoutingInMVC.Controllers  
  8. {  
  9.     public class AuthorController : Controller  
  10.     {  
  11.         // GET: Author  
  12.   
  13.   
  14.         [Route("Author/AuthorDetail")]    
  15.         public ActionResult AuthorDetail( string id, string AuthorName)  
  16.         {  
  17.             ViewBag.authorId = id;  
  18.             ViewBag.authorName = AuthorName;  
  19.             return View();  
  20.         }  
  21.     }  
  22. }  
We saw how we can define a custom route in to RouteConfig file and can call our action controller according to our RouteMap.

Thanks for reading this article. Stay tuned with me for new upcoming articles.

Connect (“Nitin Pandit”);

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now