ASP.NET C#.NET cascade DropDownList using Ajax

25 May
2009

Using dropdownlist is, for me, a good thing, It allows you to avoid input error or make some coherent choice compared with a previous input.

The deal in this post, is to make a coherent cascade dropdownlist. For example, you choose a country and you would like to auto-populate the dropdownlist States. It is a common thing in web development. To do this in ASP.NET MVC, the Ajax Controller Toolkit does not work without modifying some code. It will take you more time to setup it than it takes to write the right code in a “pure” html way with Jquery.

1) Populate the dropdownlist “Countries” :

For example, add an action in the controller of your choice, retrieve your country from a db or whatever you want.

In my case, I retrieve the country list from a service who called a db but it is not the subject here.

You pass the data to the view by the ViewData object.

public ActionResult Index()
{
var CountryList = new SelectList(_locationService.GetCountries(), "CountryRegionCode", "CountryRegionCode");

ViewData["Countries"] = CountryList

return View("index");
}

2)Add the html objects

In you view index.aspx, you add a dropdown called “Countries” like you wrote in your controller. Like this, the view can know where he has to put the country list.

Add also the other dropdown,  a select object with an id = “States”.

<p>
<label for="Countries" >Country</label>
<%= Html.DropDownList("Countries", "Select your Country")%>
</p>
<p>
<label for="StateProvinceCode">State:</label>
<select name="States" id="States">
<option value="">Select your State</option>
</select>
</p>

3) Add the javascript who will populate the dropdown “States”

If you launch your code now, you will see that the dropdrown called “countries” is well populated.

Nevertheless, the dropdown “States” is still empty. To fill in, I will use the ajax function from Jquery. It will call a function located in my controller. This action will receive the country region code and return the state list refined by the country region code (located in a db).

Here is the Javascript code to put inside the html head bracket.

<script type="text/javascript">
$(function() {
$("select#Countries").change(function() {
var countrycode = $("#Countries > option:selected").attr("value");

$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/Location/States/" + countrycode,
data: "",
dataType: "json",
success: function(data) {
if (data.length > 0) {
var options = '';
for (s in data) {
var state = data[s];
options += "<option value='" + state.Value + "'>" + state.Text + "</option>";
}
$("#States").html(options);
}
}
});
});
});

The line of code bellow allow the script to know where there is a change on the dropdownlist “Countries”.

$("select#Countries").change(function() {});

When there is a change, we encapsulate the value.

var countrycode = $("#Countries > option:selected").attr("value");

We use this variable to pass through the URL.

url: "/Location/States/" + countrycode

After, the function collects the data, build the options of an html object.

options += "<option value='" + state.Value + "'>" + state.Text + "</option>";

Finally we pass this list to the select object called “States”

$("#States").html(options);

4) Add the action method who will return the state list

If you launch that piece of code without adding the action “States” in you controller, you will receive a jscript error. So, add the action who will return the list of states you desire.

public ActionResult States(string id)
{
var StateList = new SelectList(_locationService.GetStatesProvinces(id), "StateProvinceCode", "Name");
return Json(StateList);
}

This action will receive a string id (here the CountryRegionCode), called a function from my locationservice and retrieve the states by CountryRegionCode.

We only take the value that interests us by creating a selectedlist and then we call the function Json() which will serialize the data into a json format.

If you launch again your code and change the value of the dropdownlist “Countries”, the dropdownlist States will automatically be updated.

This is the end for this post and as usual, if you have questions or feedback, leave me a comment.

Related links :

http://stephenwalther.com/blog/archive/2008/09/07/asp-net-mvc-tip-41-creating-cascading-dropdown-lists-with-ajax.aspx

http://www.michaeljbaird.com/post/2009/04/13/ASPnet-MVC-and-JQuery-Cascading-Droplist.aspx

Comment Form

top