Routing is a mechanism to shorten the route. One can create URL to view using routing.
Example
To create a URL, one have a long route which is more complex to go to the destination.So, search for a short route to go to destination. This work is done by Routing in MVC.
In Technical language, Long route means the URL which is more lengthy. Short route means the URL which one have created using routing and can create any number of URLs for views by using this routing.
How to use Routing?
Description
To use the routing, follow the below steps.
Step 1
Double click on the RoutingConfig.cs File, which is under the App_Start folder in the Solution Explorer as shown in the below code.
Step 2
Then, the following code will appear as shown in the below figure.
Step 3
Write the following code to generate URLs.
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace HelloWorld
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Home", // The name of the URL. This must be unique
url: "Home", // The URL which we have given
defaults: new { controller = "Home", action = "GotoHome", id = UrlParameter.Optional }
// The componetes which for which we have created URL
);
routes.MapRoute(
name: "Default", // Default route
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
[/csharp]
Remember
Don't delete the default URL. Because, if the zURL which we have created is not working then, the default URL will be open.
Always the Default URL must be below the newly created URL. Because, the URL which is in the first will be executed first and it will not go to the next URL, if we give the default URL as first.
Step 3
Press f5 to run the application.
Then the browser will appear. Now, type the URL as shown in the following window and press Enter.
The output will be displayed as shown in the above diagram.
Note
Remember, we just type the URL as Home. No need to write action name here.