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.
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.
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).
In the below figure, as you can see the default MVC will be selected, select MVC and then click “OK” button.
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
-
- namespace RoutingInMVC
- {
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- }
- }
- }
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.
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
- );
- }
- }
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().
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Optimization;
- using System.Web.Routing;
-
- namespace RoutingInMVC
- {
- public class MvcApplication : System.Web.HttpApplication
- {
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- BundleConfig.RegisterBundles(BundleTable.Bundles);
- }
- }
- }
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.
Give a proper name to your 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.
Add a view for this Action method, by right clicking near Action method.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace RoutingInMVC.Controllers
- {
- public class AuthorController : Controller
- {
-
-
-
- public ActionResult AuthorDetail( string id, string AuthorName)
- {
- ViewBag.authorId = id;
- ViewBag.authorName = AuthorName;
- return View();
- }
- }
- }
It takes a default name AuthorDetail for the View, click on the add button.
Call the respective parameter for Id and Name by using Razor syntax.
- @{
- ViewBag.Title = "AuthorDetail";
- }
-
- <h2>AuthorDetail</h2>
Author ID: @ViewBag.authorId<br /><br/>
Auhtor Name: @ViewBag.authorName
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”.
- routes.MapRoute(
- name: "Author",
- url: "{Author}/{AuthorID}",
- defaults: new
- {
- controller = "Author",
- action = "AuthorDetail"
-
- }
- );
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.
Now, pass an id of integer type in the Url, hence result will happen and Url as well.
Now, pass the name of author, like query string, look at the URL and result.
Defining Route attribute on controller action method,
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace RoutingInMVC.Controllers
- {
- public class AuthorController : Controller
- {
-
-
-
- [Route("Author/AuthorDetail")]
- public ActionResult AuthorDetail( string id, string AuthorName)
- {
- ViewBag.authorId = id;
- ViewBag.authorName = AuthorName;
- return View();
- }
- }
- }
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”);