ASP.NET MVC 3 Optional Parameter Routing Issue

2019-04-16 16:51发布

问题:

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.