2

In MVC 4 application while defining routing I can provide a list of default parameters. What value shall I provide for optional parameter: UrlParameter.Optional or empty string?

Examples:

routes.MapRoute("simple", "{controller}/{action}/{id}",
  new {controller = "Home", action = "Index", id = UrlParameter.Optional});
routes.MapRoute("simple", "{controller}/{action}/{id}",
  new {controller = "Home", action = "Index", id = ""});

Is there any difference between id = "" and id = UrlParameter.Optional in above examples?

Please note that some controller actions will be using id (of type string) and some will be parameterless.

Dave Alperovich
  • 32,320
  • 8
  • 79
  • 101
Alexandar
  • 916
  • 2
  • 9
  • 22

1 Answers1

4

The difference is subtle and but almost unimportant

UrlParameter.Optional means a null will be passed to the Action Method in lieu of a value.

id = "" means a default value of "" (not null) will be passed to the Action Method.

In both cases, not including an id parameter in your route will NOT stop the MVC framework from finding the right method.

In the case of UrlParameter.Optional, you should make all relatable Action Methods take a nullable parameter

Type matters

You should NOT apply id="" to routes that use ints.

Dave Alperovich
  • 32,320
  • 8
  • 79
  • 101
  • 2
    Also of importance is only the last parameter in the list can have a default value of `UrlParameter.Optional` – Forty-Two Feb 06 '13 at 20:04