AJAX Call For Dropdown Lists In MVC

In today’s article, we will see how to populate a dropdown list in MVC, using AJAX call and on the basis of the selected value's first drop down, we will populate a second dropdown list.

What is AJAX call?

AJAX call is an asynchronous request initiated by the Browser to the Server with a Postback result, which will not result in a page transition or complete page refresh.

We can partially update the page without the entire page being reloaded through AJAX call. Here, we will first create two empty drop downs, which we will populate, according to our need.

Simple syntax of dropdown list is given below. 

  1. <select id=" countryDropDownList" >  
  2.        <option value="Select">Select</option>  
  3. </select>   

This will generate a simple dropdown list with the select option only.

We have provided this control with an Id, which we will be used to populate it, using AJAX call.

Hence, with HTML of both dropdowns, my cshtml page looks, as shown below.


I have added few CSS bootstrap classes and applied some design to make the form pretty. When we run this code, the preview will be, as shown below.


Hence, country and state are the dropdowns, which are both empty. We will now populate them, using AJAX call. Now, we will write our methods in controller, which will provide us the data during AJAX call.

Declaration of the function will be, as shown below. 

  1. public JsonResult GetCountries() {}   

Here, the return type of the method will be JsonResult because we will return JSON from here.

Here, we will write our logic to retrieve the list of the countries from the database but for the demo, I will just return a list string from here. Also for the states, we will write the method with some hard coded values for the demo.

Now, our GetCountries method will look, as shown below. 

  1. public JsonResult GetCountries()  
  2.         {  
  3.             var Countries = new List<string>();  
  4.             Countries.Add("Australia");  
  5.             Countries.Add("India");  
  6.             Countries.Add("Russia");  
  7.             return Json(Countries, JsonRequestBehavior.AllowGet);  
  8.         }   

We have added three countries in a list. You can add your logic to get the list from the database.

Now, the method for states looks, as shown below. 

  1. [HttpPost]  
  2.         public JsonResult GetStates(string country)  
  3.         {  
  4.             var States = new List<string>();  
  5.             if (!string.IsNullOrWhiteSpace(country))   
  6.             {  
  7.                 if (country.Equals("Australia"))   
  8.                 {  
  9.                     States.Add("Sydney");  
  10.                     States.Add("Perth");  
  11.                 }  
  12.                 if (country.Equals("India"))  
  13.                 {  
  14.                     States.Add("Delhi");  
  15.                     States.Add("Mumbai");  
  16.                 }  
  17.                 if (country.Equals("Russia"))  
  18.                 {  
  19.                     States.Add("Minsk");  
  20.                     States.Add("Moscow");  
  21.                 }  
  22.             }  
  23.             return Json(States, JsonRequestBehavior.AllowGet);  
  24.         }   

We have created GetStates method [HttpPost] because we need to pass the selected country on the basis of which we will get the state. Hence, in order to pass the selected country securely, we have created it as Post method.

Now, the controller part is done. We will now move on to the script part.

Our controller looks, as shown below.


Now, in our cshtml page, we will include jQuery JS file.

  1. <script src="~/Scripts/jquery-1.10.2.js"></script>   

Now, we will start a script tag in which we will create a function for AJAX call and we will have the document.ready function, which fires automatically when the page is completely loaded. 

  1. $(function () {  
  2.     });  
  3.   
  4.     function AjaxCall(url, data, type) {  
  5.         return $.ajax({  
  6.             url: url,  
  7.             type: type ? type : 'GET',  
  8.             data: data,  
  9.             contentType: 'application/json'  
  10.         });  
  11.     }  
  12. Here this $(function () {  
  13.     });   

AJAX call function is what we will use for AJAX calls. On Document ready function, we will use AJAX call to populate the country. Here, the code is given below for it. 

  1. AjaxCall('/Dummy/GetCountries'null).done(function (response) {  
  2.             if (response.length > 0) {  
  3.                 $('#countryDropDownList').html('');  
  4.                 var options = '';  
  5.                 options += '<option value="Select">Select</option>';  
  6.                 for (var i = 0; i < response.length; i++) {  
  7.                     options += '<option value="' + response[i] + '">' + response[i] + '</option>';  
  8.                 }  
  9.                 $('#countryDropDownList').append(options);  
  10.             }  
  11.         }).fail(function (error) {  
  12.             alert(error.StatusText);  
  13.         });   

Here, we have checked the length of the response and we need to empty HTML of the select tag with its Id and through the response, we have appended our options HTML into the select tag.


Now, we have to populate the state dropdown, when we select any country from the country list.

For it, the code is given below. 

  1. $('#countryDropDownList').on("change"function () {  
  2.             var country = $('#countryDropDownList').val();  
  3.             var obj = { country: country };  
  4.             AjaxCall('/Dummy/GetStates', JSON.stringify(obj),'POST').done(function (response) {  
  5.                 if (response) {  
  6.                     $('#stateDropDownList').html('');  
  7.                     var options = '';  
  8.                     options += '<option value="Select">Select</option>';  
  9.                     for (var i = 0; i < response.length; i++) {  
  10.                         options += '<option value="' + response[i] + '">' + response[i] + '</option>';  
  11.                     }  
  12.                     $('#stateDropDownList').append(options);  
  13.   
  14.                 }  
  15.             }).fail(function (error) {  
  16.                 alert(error.StatusText);  
  17.             });  
  18.         });   

Here, we have invoked the on change method of the country dropdown list, using its Id and then we have called our method in controller, using AJAX call.

We have provided ‘POST’ in the type parameter because we have made the method HttpPost in controller.

The output is given below.


By selecting Australia, states are Sydney and Perth.


On selecting India, it is showing Delhi,Mumbai\

The entire script tag is given below. 
  1. <script>  
  2.   
  3.     $(function () {  
  4.   
  5.         AjaxCall('/Dummy/GetCountries'null).done(function (response) {  
  6.             if (response.length > 0) {  
  7.                 $('#countryDropDownList').html('');  
  8.                 var options = '';  
  9.                 options += '<option value="Select">Select</option>';  
  10.                 for (var i = 0; i < response.length; i++) {  
  11.                     options += '<option value="' + response[i] + '">' + response[i] + '</option>';  
  12.                 }  
  13.                 $('#countryDropDownList').append(options);  
  14.   
  15.             }  
  16.         }).fail(function (error) {  
  17.             alert(error.StatusText);  
  18.         });  
  19.   
  20.         $('#countryDropDownList').on("change"function () {  
  21.             var country = $('#countryDropDownList').val();  
  22.             var obj = { country: country };  
  23.             AjaxCall('/Dummy/GetStates', JSON.stringify(obj),'POST').done(function (response) {  
  24.                 if (response.length > 0) {  
  25.                     $('#stateDropDownList').html('');  
  26.                     var options = '';  
  27.                     options += '<option value="Select">Select</option>';  
  28.                     for (var i = 0; i < response.length; i++) {  
  29.                         options += '<option value="' + response[i] + '">' + response[i] + '</option>';  
  30.                     }  
  31.                     $('#stateDropDownList').append(options);  
  32.   
  33.                 }  
  34.             }).fail(function (error) {  
  35.                 alert(error.StatusText);  
  36.             });  
  37.         });  
  38.   
  39.     });  
  40.   
  41.     function AjaxCall(url, data, type) {  
  42.         return $.ajax({  
  43.             url: url,  
  44.             type: type ? type : 'GET',  
  45.             data: data,  
  46.             contentType: 'application/json'  
  47.         });  
  48.     }  
  49. </script>   

Summary

In this article, we learned how to populate dropdown, using AJAX call without refreshing the entire page and populated another dropdown on the basis of the selected value of the first drop down.