in this articel we will discuss briefly about routing in mvc
What we will learn this article
- what is routing in MVC
- how to Mapping URL to Controller Action Method
- how to Resolving Namespace Ambiguity
- how to Ignoring Routes
- how to implement Attribute Routing in MVC 5
- how to Apply Constraints on Route parameters
What is routing in MVC?
this MVC framework uses the ASP.NET routing engine, which provides flexibility for mapping URLs to controller classes.
MVC uses in order to evaluate incoming URLs and to select the appropriate controller
MVC framework passes the values to the controller action methods as parameters.
By default Global URL Routing :
The Asp.net MVC Routes are initialized in the Application_Start method of the Global.asax file.
the Global.asax class can have a RourteConfig.RegisterRoutes which includes default routing logic data. see the given below example.
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { RouteConfig.RegisterRoutes(RouteTable.Routes); } 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 } ); } }

how to Mapping URL to Controller Action Method
let see the example for Implementing Routing for Product Application Add the following route methods to the Global.asax class
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Create", // Route name "CreatePro", // URL with parameters new { controller = "Product", action = "Create" } // Parameter defaults ); routes.MapRoute( "Edit", // Route name "EditPro/{Id}", // URL with parameters new { controller = "Product", action = "Edit" } // Parameter defaults ); routes.MapRoute( "Delete", // Route name "DeletePro/{id}", // URL with parameters new { controller = "Product", action = "Delete" } // Parameter defaults ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }
Note: All the entries must be above “Default” route
URL Structure | Controller | |||
http://localhost:6737/ | HomeController | |||
http://localhost:6737/Product | ProductController | |||
http://localhost:6737/Product/Create | ProductController | |||
http://localhost:6737/Product/Edit/3 | ProductController |
how to Resolving Namespace Ambiguity
in your Application If you have two HomeController Classes in different namespaces.at this time we have two options one is namespaces constraint or we will use ControllerBuilder class
let see the given below code for resolving namespace ambiguity in routing in MVC.
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new[] { "MyTestApp.Controllers" } ); //OR ControllerBuilder.Current.DefaultNamespaces.Add("MyTestApp.Controllers");
How to Ignoring Routes
in your asp.net Application In case we don’t want routing to be applied for a particular type of document or URL. for that we will use IgnoreRoute() method.
routes.IgnoreRoute("Home/Index/567");
once we will ignore the specify type URL, if we will try fect the URL it will show to us 404.0 – Not Found
then the URL: http://localhost:49165/Home/Index/567
will render HTTP Error 404.0 – Not Found
How to implement Attribute Routing in MVC 5
Right-click in your App_Start folder Add a class RouteConfig.cs and you will add routes.MapMvcAttributeRoutes(); This must be added before the route table configuration.
[RoutePrefix("Demo")] public class ProductController : Controller { // eg.: /Product [Route] public ActionResult Index() { } // eg.: /Product/create [Route("Create")] public ActionResult Create(int id) { } // eg.: /Product/4/edit [Route("{id}/Edit")] public ActionResult Edit(int id) { } }
what is rought Route Names?
You can specify a name for a route at the controller level or action method level also, in order to easily allow URI generation for it. For example
[Route("Layout", Name="headerMenu")] public ActionResult HeaderMenu() { }
<a href="@Url.RouteUrl("headerMenu")">Header Menu</a>
How to Apply Constraints on Route parameters
routes.MapRoute( name: "Default", url: "{controller}/{action}/{name}/{id}", defaults: new { controller = "Home", action = "Index", name="test", id = UrlParameter.Optional }, constraints: new { name="[a-z]{5}", id = @"\d{1,8}" } );
[Route("users/{id:int}"] public ActionResult GetId(int id) { } // eg: users/username [Route("users/{name}"] public ActionResult GetUserByName(string name) { }
Here, the first route will only be selected if the “id” segment of the URI is an integer. Otherwise, the second route will be chosen. you will see attribute route constraints in MVC
Test your Skills:
Interview Questions and Answers
- How to create dynamic form fields using jQuery - January 4, 2021
- What is CTS (Common Type System) in .Net - October 16, 2020
- What is main method in c# - October 13, 2020
Thanks for your information, you have given very useful and important information.Best Choice
https://nareshit.com/asp-net-mvc-online-training/