i

ASP.Net A Complete Guide

Routing in MVC

Routing means a route for an incoming request. Let's say you want to access some page then how the browser knows that what page you are requesting. Routing helps us to map the URL requested in the browser with the action present in the requested controller.

The Routing helps to eliminate the needs of mapping URL with a physical file. Route defines the pattern of the URL with the Handler information.

Route is registered in the RouteConfig file. MVC has the route table framework. All the route and their patterns are registered here.

Example:

public class RouteConfig

{

    public static void RegisterRoutes(RouteCollection routes)

    {

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 

        routes.MapRoute(

            name: "Employee",

            url: "Employee/{id}",

            defaults: new { controller = "Employee", action = "Index"}

        );

        routes.MapRoute(

            name: "Default",

            url: "{controller}/{action}/{id}",

            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

        );

    }

}

 

Route Property:

  • Route Name: The route name is a reference given to the specific route.

  • URL Pattern: A URL pattern may contain literal values and variables. The literals and placeholders are located in segments of the URL that are delimited by the slash (/) character.

  • Defaults: It defines the default value for a parameter.

  • Constraints: A set of validations applied to the URL pattern.

Example:

Sr.No

URL

Parts of URL

1

Employee/Index

Controller= Employee ,Action= Index

2

Employee/Details/112233

Controller= Employee ,Action= Details,Parameter=112233