MVC 4 Default Parameter Value

£可爱£侵袭症+ 提交于 2020-01-04 08:29:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!