Search code examples
c#asp.net-mvcasp.net-routing

ASP.NET MVC Routing? // UrlParamter.Optional Vs Empty String


What is the actual difference between these two routes ?

&

These two routes are the same?

//Route 1.
routes.MapRoute("SampleRounteOne" , "{controller}/{action}/{id}" , new {id = UrlParamter.Optional})

//Route 2.
routes.MapRoute("SampleRounteTwo" , "{controller}/{action}/{id}" , new {id = ""})

Solution

  • No! These two routes are not the same.

    //Route1
    route.MapRoute("Route1" , "{controller}/{action}/{id}" , new { id = UrlParameter.Optional});
    

    The same thing can also be acomplished by setting the id to be an empty string: { id : ""}

    for example:

    //Route 2.
    routes.MapRoute("Route2" , "{controller}/{action}/{id}" , new {id = ""})
    

    This seems a lot short/breif, so why not we use this ?

    What is the difference?

    First thing:

    you asking that : These two routes are the same?

    No! these two routes are not same.

    Now Come to the point!

    What is the actual difference between these two routes?

    When we type URL parameters values are parsed out of the URL and put into a dictionary?

    Now When we use UrlParameter.Optional as a default value and no value is supplied in the URL, Routing does'nt even add an entry to the dictionary. If the default value is set to an empty string, the route value dictionary will contain a value with the key "id" and the value as an empty string. In some cases, this distincition is important it lets you know the difference between the id not being specified, and it being specified but left empty.