MVC - Cascading Lists using Ajax and jQuery
It seems like every project I'm on has a cascading list requirement. The problem is common enough: once a value in one list is selected, a second sub-list is populated based on selections from the first. One of the most common scenarios (as seen above) is selecting a Country, which populates a list of States or Provinces (or Cities for my example).
In a recent project, an additional requirement of cascading multi-select lists was needed. If the user selects multiple values in the first list, the second list should contain all of the sub-selections from all the selections in the first list.
Typically in the past, this has been done via post-back to the server to populate the second list. This has the disadvantage of refreshing the page, which means the user is stuck waiting. However, in MVC, it is just as simple to use Ajax and Jquery to seamlessly populate the list without interrupting the user experience.
First, the models. This example is pretty simple. We have a Country object, and a City object that contains a reference to the Country.
Code Snippet
- public class Country
- {
- public int CountryId { get; set; }
- public string Name { get; set; }
- }
Code Snippet
- public class City
- {
- public int CityId { get; set; }
- public int CountryId { get; set; }
- public string Name { get; set; }
- }
Next, we need a place to capture the selected CountryIds and CityIds, so our view model looks like so:
Code Snippet
- public class HomeModel
- {
- public List<int> SelectedCountryIds { get; set; }
- public List<int> SelectedCityIds { get; set; }
- }
On the controller, a ViewBag is populated with the Countries (generally retrieved from a repository). This will allow us to bind to that list on the view. Note: It's not necessary to populate the ViewBag with Cities; we will do that via Ajax as the user makes selections.
Code Snippet
- public ActionResult Index()
- {
- //Populate a list of Countries.
- ViewBag.Countries = FakeRepository.GetCountries();
- return View();
- }
On the view, we bind the two lists to the HomeModel.
Code Snippet
- @Html.ListBoxFor(x => x.SelectedCountryIds, new MultiSelectList(ViewBag.Countries, "CountryId", "Name"))
- @Html.ListBoxFor(x => x.SelectedCityIds, new MultiSelectList(new List<City>(), "CountryId", "Name"))
Note that our city list is populated with an empty List<City>().
That's the setup. All that's left is to create a method on the controller to get a city list based on a list of countries (or countryIds in this case), and the jQuery to make the Ajax call.
I use POST to prevent access via URL to the GetCities(), but GET works as well. Note that we pass the model to the Json() method. This will translate the model into an object usable by jQuery.
Code Snippet
- [HttpPost]
- public ActionResult GetCities(List<int> countryIds)
- {
- if (countryIds == null)
- return Json(null);
- //Select cities from the list matching the selected counties
- List<City> selectedCities = FakeRepository.GetCitiesByCountryIds(countryIds);
- //Return a Json object to the Success fucntion of the Ajax call
- return Json(selectedCities);
- }
Finally, we need some jQuery to put it all together. We'll hook a function to the click() method of the Countries list. We iterate over all of the selected countries and store the values in an array. Finally, we send the array to the Controller using jQuery's $.ajax call. In the success function, the city list is populated with the new options returned from the controller.
Code Snippet
- <script type="text/javascript">
- $(function () {
- //Change the City list each time the Country list is selected
- $('#SelectedCountryIds').change(function () {
- var selectedCountryIds = [];
- //Iterate over each selection in the Country list and add
- //its CountryId to the array
- $('#SelectedCountryIds option:selected').each(function () {
- selectedCountryIds.push($(this).val());
- });
- //Ajax the CountryId list to the GetCities() method in the HomeController
- $.ajax({
- url: '@Url.Content("~/Home/GetCities/")',
- dataType: 'json',
- type: 'POST',
- data: JSON.stringify(selectedCountryIds),
- contentType: 'application/json',
- success: function (cities) {
- //Empty the City List of previous values
- $('#SelectedCityIds').empty();
- //Iterate over each city and append it to the City List
- $(cities).each(function () {
- $('#SelectedCityIds').append('<option value="' + this.CityId + '">' + this.Name + '</option>');
- });
- }
- });
- });
- });
- </script>
Thats it. Holding down CTRL while clicking the Country list will add those Cities to the City list, all without refreshing the page.
Just one little gotcha, it is important to specify the contentType option as 'application/json' in the Ajax call. Without it, the controller won't interpret the data as Json, and the contryIds list will be null.
Comments
Post a Comment