Web Programming TutorialsLearn the Concept of Routing in MVC

Learn the Concept of Routing in MVC

MVC_Route

Hi friends, today we are going to learn about MVC routing.

Routing is nothing but a pattern matching system which manages the incoming request. In MVC, Route engines use the Route table for matching the requested URL pattern with the URL patterns defined in Route table. We can register Route table at Application Start event. MVC5 also supports attribute routing.
What is Routing

Routing Engine uses Routing rules which are defined in Application_Start() method of Global.asax file.
As you can see below. When you create MVC application, the code below is automatically added in global file.

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            RouteConfig.RegisterRoutes(RouteTable.Routes);

            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }

1

Learn HTML5 Programming For Beginners

We can find RouteConfig.cs file under App_Start folder where the below method is written. This method contains the route collection. We can add our Map Route according to the requirement. Map Route contains some parameters:

1st parameter is the name for the route
2nd parameter represents the URL that will be our controller, then action followed by id (if any)
3rd default controller will be Home, default action will be Index and Id is optional

public static void RegisterRoutes(RouteCollection routes)
            {
            
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                );
            }

2

Finally URL Engine evaluates something as “http://localhost:11234/Home/Index”, where Home is our controller and Index is its Action. So, request will be forwarded to Home Controller’s Index Action. Because of the default routing rule, request is forwarded to the same controller action in all following cases:

  1. http://localhost: 11234/
  2. http://localhost: 11234/Home
  3. http://localhost: 11234/Home/Index

Summary: In the example above, we have learned about MVC routing.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -