I would suggest you creating an action which will return a JSON representation of all the companies for a selected country:
public class CompaniesController: Controller
{
public ActionResult List(string countryId)
{
IEnumerable<Company> companies = Repository.GetCompanies(countryId);
// Let's assume that Company has two properties: Id and Name
return Json(companies);
}
}
Then assuming you already have a dropdown bound to the countries:
<%= Html.DropDownListFor(x => x.Country, Model.Countries) %>
<%= Html.DropDownListFor(x => x.Company, Enumerable.Empty<SelectListItem>()) %>
you could register for the onchange
event and when this event occurs perform an AJAX call to the List
action of the Companies
controller and get the associated companies:
$(function() {
$('select#Country').change(function() {
var countryId = $(this).val();
$.post('/companies/list', { countryId: countryId }, function(companies) {
var companiesSelect = $('select#Company');
// loop through the companies and fill the dropdown
$(companies).each(function(index, company) {
companiesSelect.append(
'<option value="' + company.Id + '">'
+ company.Name +
'</option>');
});
});
});
});