简体   繁体   中英

MVC 4 Default Parameter Value

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM