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.
- <select id=" countryDropDownList" >
- <option value="Select">Select</option>
- </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.
- 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.
- public JsonResult GetCountries()
- {
- var Countries = new List<string>();
- Countries.Add("Australia");
- Countries.Add("India");
- Countries.Add("Russia");
- return Json(Countries, JsonRequestBehavior.AllowGet);
- }
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.
- [HttpPost]
- public JsonResult GetStates(string country)
- {
- var States = new List<string>();
- if (!string.IsNullOrWhiteSpace(country))
- {
- if (country.Equals("Australia"))
- {
- States.Add("Sydney");
- States.Add("Perth");
- }
- if (country.Equals("India"))
- {
- States.Add("Delhi");
- States.Add("Mumbai");
- }
- if (country.Equals("Russia"))
- {
- States.Add("Minsk");
- States.Add("Moscow");
- }
- }
- return Json(States, JsonRequestBehavior.AllowGet);
- }
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.
- <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.
- $(function () {
- });
-
- function AjaxCall(url, data, type) {
- return $.ajax({
- url: url,
- type: type ? type : 'GET',
- data: data,
- contentType: 'application/json'
- });
- }
- Here this $(function () {
- });
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.
- AjaxCall('/Dummy/GetCountries', null).done(function (response) {
- if (response.length > 0) {
- $('#countryDropDownList').html('');
- var options = '';
- options += '<option value="Select">Select</option>';
- for (var i = 0; i < response.length; i++) {
- options += '<option value="' + response[i] + '">' + response[i] + '</option>';
- }
- $('#countryDropDownList').append(options);
- }
- }).fail(function (error) {
- alert(error.StatusText);
- });
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.
- $('#countryDropDownList').on("change", function () {
- var country = $('#countryDropDownList').val();
- var obj = { country: country };
- AjaxCall('/Dummy/GetStates', JSON.stringify(obj),'POST').done(function (response) {
- if (response) {
- $('#stateDropDownList').html('');
- var options = '';
- options += '<option value="Select">Select</option>';
- for (var i = 0; i < response.length; i++) {
- options += '<option value="' + response[i] + '">' + response[i] + '</option>';
- }
- $('#stateDropDownList').append(options);
-
- }
- }).fail(function (error) {
- alert(error.StatusText);
- });
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.
- <script>
-
- $(function () {
-
- AjaxCall('/Dummy/GetCountries', null).done(function (response) {
- if (response.length > 0) {
- $('#countryDropDownList').html('');
- var options = '';
- options += '<option value="Select">Select</option>';
- for (var i = 0; i < response.length; i++) {
- options += '<option value="' + response[i] + '">' + response[i] + '</option>';
- }
- $('#countryDropDownList').append(options);
-
- }
- }).fail(function (error) {
- alert(error.StatusText);
- });
-
- $('#countryDropDownList').on("change", function () {
- var country = $('#countryDropDownList').val();
- var obj = { country: country };
- AjaxCall('/Dummy/GetStates', JSON.stringify(obj),'POST').done(function (response) {
- if (response.length > 0) {
- $('#stateDropDownList').html('');
- var options = '';
- options += '<option value="Select">Select</option>';
- for (var i = 0; i < response.length; i++) {
- options += '<option value="' + response[i] + '">' + response[i] + '</option>';
- }
- $('#stateDropDownList').append(options);
-
- }
- }).fail(function (error) {
- alert(error.StatusText);
- });
- });
-
- });
-
- function AjaxCall(url, data, type) {
- return $.ajax({
- url: url,
- type: type ? type : 'GET',
- data: data,
- contentType: 'application/json'
- });
- }
- </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.