views:

247

answers:

1

I'd like to achieve the following 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?

+1  A: 

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>');
            });
        });
    });
});
Darin Dimitrov
Thanks, it works. It gives me the impression of an ad hoc solution, though. I am still kinda confused of how to build generic, as Telerik calls them, MVC extensions, as it used to be the case with user controls before. I am afraid that the code could get messy, if I start writing an extension that is supposed to work for many cases