How do I use Optional Parameters in an ASP.NET MVC Controller

The string should be ok, as it’ll get passed as an empty string. For int, make it nullable:

public ActionResult Index(string Country, int? Regions)

Also, you’ll note I capitalized it in the same was as your querystring.

Edit

Note that ASP.NET now allows you to define default parameters. E.g.:

public ActionResult Index(string Country, int Regions = 2)

However, IMHO I’d recommend that you only use the default where it makes semantic sense. For example, if the purpose of the Regions parameter were to set the # of regions in a country, and most countries have 2 regions (North and South) then setting a default makes sense. I wouldn’t use a “magic number” that signifies a lack of input (e.g., 999 or -1) — at that point you should just use null.

Leave a Comment