1

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
  • If so, how would you want to define your url pattern? If the pattern can be distinctive, you should just map it as another routing entry Commented Jan 4, 2012 at 4:30

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.