ASP.NET MVC 3 Optional Parameter Routing Issue

吃可爱长大的小学妹 提交于 2019-12-12 09:18:57

问题


http://blogs.msdn.com/b/simonince/archive/2011/02/02/asp-net-mvc-3-optional-parameter-routing-issue.aspx

The workaround mentioned in the above site is acceptable. But what will happen if the last parameter is not optional and the first two are optional in MVC3?. Can anybody know the workaround. Its just a doubt which is confusing me.


回答1:


In an MVC3 route definition, only the last parameter can be optional. As Nat hints at, you can create multiple routes for the same controller action method.

If you want to have one required parameter and 2 optional parameters, you can define multiple routes:

...MapRoute(null, "static-segment/{required}/{optional1}/{optional2}", 
    new { controller = "ControllerName", action = "ActionName", 
        optional2 = UrlParameter.Optional });

...MapRoute(null, "static-segment/{required}/{optional1}", 
    new { controller = "ControllerName", action = "ActionName", 
        optional1 = UrlParameter.Optional });

...MapRoute(null, "static-segment/{required}/{optional2}", 
    new { controller = "ControllerName", action = "ActionName", 
        optional2 = UrlParameter.Optional });

Having a single route where there are 2 optional parameters is something you can't do in MVC3. Also, having an optional parameter come before a required parameter in a route is something you can't do in MVC3. You need to flesh out all of the routing pattern scenarios and create routes that will match each case in your URL schema.



来源:https://stackoverflow.com/questions/8721994/asp-net-mvc-3-optional-parameter-routing-issue

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