Search code examples
asp.net-mvcasp.net-mvc-4url-routingasp.net-mvc-routing

Understanding MVC routing conventions


I am looking at an example of MVC Route and it looks like following:

routes.MapRoute("Cuisine", "cuisine/{name}", new 
{ controller = "Cuisine", action = "Search", name = ""})

I am just trying to dissect what each element stands for here:

"cuisine/{name}"

Does this part say that if a request comes with URL starting from word cuisine and there is a second string parameter and route it to this particular Route and consider second part of URL as parameter name?

{ controller = "Cuisine", action = "Search", name = ""})

If nothing is passed into the parameter then please use empty string as default and if some value is passed for name parameter then use that value?


Solution

  • "cuisine/{name}"

    . Does this part say that if a request comes with URL starting from word cuisine and there is a second string paramter and route it to this particular Route and consider second part of URL as parameter name?

    Yes, that is correct.

    { controller = "Cuisine", action = "Search", name = ""})

    If nothing is passed into the parameter then please use empty string as default and if some value is passed for name parameter then use that value?

    Yes, that is also correct. However, it is usually more sensible to specify an optional parameter as UrlParameter.Optional.

    Basically, there are 2 (important) parts to a route configuration.

    There is a match specification which always consists of the URL parameter and may also include constraints, optional, and required values. A required value is one where you don't specify any default for a route key and also include it as a route segment. If a route doesn't fit the criteria of the match, the framework will attempt the next route in the configuration until it finds a match (or not). It is helpful to think of it as a switch case statement.

    Then there is a route value specification. This is a combination of the default values and any incoming URL segments that may override or add to them. Note that constant parts of the URL are not included in the route values. The only reason why "Cuisine" is inserted into the route values in your example is because it is defined as a default route value.