Do you need to use a particular Ajax libarary?
The Ajax.Net Control Toolkit has the Cascading Dropdown control pre-built for this functionality.
Missed the MVC part, in which case the Ajax Control Toolkit won't work. jQuery is probably the best option, since it makes Ajax extremely easy to code and MS is officially supporting it in conjunction with the MVC framework.
If you created a RESTful service on your site (there should be plenty of documentation on how to do this) you can return a json response through jQuery like this:
The markup:
<select id="opt1">
<option value='1'>Option 1</option>
<option value='2'>Option 2</option>
</select>
<select id="opt2" disabled></select>
Assuming the service will accept 'id' as a parameter and return a json object using this schema for example:
[
{ name: 'option1', value: '1'},
{ name: 'option2', value: '2'}
]
You'd add this javascript to the page:
$(function() {
$('select#opt1').change(function(){
$.getJSON('/data/myservice',{id: this.value},
function(response) {
var options = '';
for (var i = 0; i < response.length; i++) {
options += "<option value='" + response[i].value + "'>"
+ response[i].name + "</option>";
}
$('select#opt2').removeAttr('disabled').html(options);
});
});
});
A quick explanation of what's going on there; jQuery code can be a bit like peeling an onion, so I'll take it a level at a time:
$(function(){})
is shorthand for $(document).ready(function(){})
, so it runs the function when the ready event fires.
$('select#opt1').change(function(){})
finds the <select>
named 'opt1' and runs the function when the change event fires.
$.getJSON()
does the Ajax call for you. JSON responses are returned as strings, and have to be parsed into JSON objects, which $.getJSON does for you automatically. The first field is the url of the service, the second is a name/value pair that is converted to a querystring, and the third is the callback function to handle the response.