问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/14737610/mvc-4-default-parameter-value