Optional Parameters with AttributeRouting

posted on 27 Nov 2011 | ASP.NET MVC

I found a little trick with using Optional Parameters with AttributeRouting, by using standard optional parameters in the action.

The documentation says you can add an attributes to specify the defaults, or add =value to the parameter name, and I guess that's a more correct way to generate routes, but you can achieve the same affect by making the parameter optional. Like so:

public ActionResult Videos(int page = 1)
    return View("Result");

If I browse to the URL:

It uses the default value of 1.

Now when appending a number to the end of the URL:

It captures the correct value:

I prefer this method, the optional parameter on the action is more quickly identified, than looking at the attribute to see the defaults. (in my opinion)

Ahh AttributeRouting, how I love you.

comments powered by Disqus