Is it possible to bind data asynchronously between two dropdownlists in a view?
I'd like to achieve the foll开发者_如何学Pythonowing effect using ASP.NET MVC and JQuery.
I've got a drop down list displaying a list of Countries. I want to make it so that when I change the value of the country, a new drop down list appears below it, showing a list of companies whose country of origin is the particular selected company. The thing is that I do not want to rely too much on controller actions because I'm using it in a Template Helper which is a "headless" view. Can I bind it somehow?
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>');
});
});
});
});
精彩评论