Chris McKee Chris McKee - 3 months ago 16
C# Question

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

I have a set of drop down controls on a view that are linked to two lists.

//control
ViewData["Countries"] = new SelectList(x.getCountries().ToList(), "key","value",country);
ViewData["Regions"] = new SelectList(x.getRegions(country).ToList(), "id", "name", regions);

/*
on the view
*/

<% using (Html.BeginForm("","", FormMethod.Get))
{ %>
<ol>
<li>
<%= MvcEasyA.Helpers.LabelHelper.Label("Country", "Country:")%>
<%= Html.DropDownList("Country", ViewData["Countries"] as SelectList) %>
<input type="submit" value="countryGO" class="ddabtns" />
</li>
<li>
<%= MvcEasyA.Helpers.LabelHelper.Label("Regions", "Regions:")%>
<%= Html.DropDownList("Regions", ViewData["Regions"] as SelectList,"-- Select One --") %>
<input type="submit" value="regionsGO" class="ddabtns" />
</li>
</ol>
<br />
<input type="submit" value="go" />
<% } %>


So its sending a query to the same page (as its only really there to provide an alternative way of setting/updating the appropriate dropdowns, this is acceptable as it will all be replaced with javascript).

The url on clicking is something like...

http://localhost:1689/?country=FRA&regions=117


Regions is dependent on the country code.

I'm trying to achieve this bit without bothering with routing as there's no real point with regards this function.

So the Controller has the following method.

public ActionResult Index(string country, int regions)

Answer

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.

Comments