代码改变世界

MVC中UrlParameter.Optional作用

2011-08-10 21:42  cnb_mtime  阅读(7434)  评论(1编辑  收藏  举报

编辑器加载中...

就像默认的路由配置, 我们可以指定默认值UrlParameter.Optional.
	routes.MapRoute(null, "Catalog/{page}",
	    new { controller = "Products", action = "List", page = UrlParameter.Optional });
这样, 当访问的URL有page值的时候, 我们就采用传入的vallue, 如果没有, 那么我们就不想action方法中传任何参数.你可能会疑惑, 为什么不用0或者是null 作为默认参数, 
下面是它的两个原因: If your action method takes a page parameter of type int, then because that type can’t hold null, you would have to supply the default value of 0 or
some other int value. This means the action method would now always receive a legal value for page, so you wouldn’t be able to control the default value
 using the MVC Framework’s [DefaultValue] attribute or C# 4’s optional parameter syntax on the action method itself (you’ll learn more about these in the
 next chapter). 如果你的action方法有个int类型的page参数,但是它是值类型, 不能是null. 所以你需要提供一个默认值(0或者是其他的值). 这也以为着action方法总是需要一个合法的值,
所以, 如果action方法自身使用mvc框架的[defaultvalue]特性或者是C#4的可选参数语法, 你将无法控制它的类型.(你会在接下来的一章中了解更多) Even if your action’s page parameter was nullable, there’s a further limitation. When binding incoming data to action method parameters, the MVC
Framework prioritizes routing parameter values above query string values (you’ll learn more about value providers and model binding in Chapter 12).
So, any routing value for page—even if it’s null—would take priority and hide any query string value called page. 即时你的action的page参数可以是null类型. 这里还有个限制. 当action方法的参数是binding类型的时候, mvc 框架会将路由参数优先于查询字符串值.(你会在12章中学到
值提供者和模型绑定). 所以, 任何为page设置的路由值--即使是null--也会优先于访问page的查询字符串 UrlParameter.Optional解决了这两个问题