What is Routing in MVC ASP.NET and How to use routing

Routing

It maps request URL to a specific controller action using a Routing Table. It is used to make user friendly URL.

Example :
URL without routing : http://locahost:XXXX/Employee.aspx?Id=10
URL with rotuing : http://locahost:XXXX/Employee/10/

In ASP.NET MVC we can use Routing in two ways..
  1. Traditional routing
  2. Attribute routing


Traditional routing :

Go to RouteConfig.cs in App_Start folder:
Copy the marked code as in image and past above it



Now let suppose that we have a view named “About” and we want that when user type http://locahost:XXXX/WhoAreYou in the URL then this page will displayed.
For this we edit RouteConfig code as follows.



Now Run the Project and go to URL like this
http://locahost:XXXX/WhoAreYou
There you can see the About page.

Attribute Routing :

Attribute routing is easier then traditional routing.
Enabling Attribute Routing:
To enable attribute routing, call MapMvcAttributeRoutes during configuration, as shown in image



Now go to Home controller and add this [Route(“URL”)] above the action method we want to route.
For example

[Route("JoinUs")]
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";

return View();
}

No Run the project and go to URL like this
http://locahost:XXXX/JoinUs

You can see the “Contact” page there. This is the simple attribute routing.

Now lets take some examples of routing with parameters.
Go to Home controller and following code to “About” action method

[Route("AboutUs/{id?}/{sec?}")]
public ActionResult About(int id,string sec)
{
ViewBag.id = id;
ViewBag.sec = sec;
return View();
}
Now go to “About” view to receive id and sec there . To do so,add following code there

<h1>Id : @ViewBag.id</h1>
<h1>Sec: @ViewBag.sec</h1>

Now run the project and go to the URL like this

http://locahost:XXXX/AboutUs/2/B

following output will be there

---------------------------
Video Tutorial