This project is read-only.


Aug 24, 2011 at 8:49 AM


就像默认的路由配置, 我们可以指定默认值UrlParameter.Optional.
    routes.MapRoute(null, "Catalog/{page}",
        new { controller = "Products", action = "List", page = UrlParameter.Optional });
这样, 当访问的URL有page值的时候, 我们就采用传入的vallue, 如果没有, 那么我们就不想action方法中传任何参数.你可能会疑惑, 为什么不用0或者是null 作为默认参数, <BR>下面是它的两个原因:
    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 <BR>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<BR> 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<BR> next chapter).
    如果你的action方法有个int类型的page参数,但是它是值类型, 不能是null. 所以你需要提供一个默认值(0或者是其他的值). 这也以为着action方法总是需要一个合法的值, <BR>所以, 如果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 <BR>Framework prioritizes routing parameter values above query string values (you’ll learn more about value providers and model binding in Chapter 12). <BR>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章中学到<BR>值提供者和模型绑定). 所以, 任何为page设置的路由值--即使是null--也会优先于访问page的查询字符串