Bind DropDown Using jQuery AJAX

Here, I am going to explain how to bind dropdown menu using jQuery AJAX. Follow the below steps.

Step 1

Add one .aspx web page to your ASP.NET application.

Step 2

Create a class CountryList with the following properties.

  1. public class CountryList  
  2.    {  
  3.        public int CountryId { get; set; }  
  4.        public string CountryName { get; set; }  
  5.    }  

Step 3

Create a Static method to return the data to AJAX call. I have created a List of CountryList to add CountryId and CountryName.

Notes

  1. The method should be static.
  2. The method should be a WebMethod.
  3. WebMethod is available inside System.Web.Services namespace.
    1. [WebMethod]  
    2. public static List<CountryList> GetCountriesName()  
    3. {  
    4.     List<CountryList> lst = new List<CountryList>();  
    5.     lst.Add(new CountryList() { CountryId=1,CountryName="India"});  
    6.     lst.Add(new CountryList() { CountryId = 2, CountryName = "Nepal" });  
    7.     lst.Add(new CountryList() { CountryId = 3, CountryName = "America" });  
    8.     return lst;  
    9.   
    10. }  

Step 4

Now, it is time to write jQuery AJAX code. Add this jQuery script to the head section of your .aspx page.

  1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  

Create a dropdown menu to bind data.

  1. <select id="ddlNationality"><option value="0" >--Select Country--</option></select>  

Write jQuery Ajax to call WebMethod (GetCountriesName) and bind the returning data to dropdown.

  1. <script type="text/javascript">  
  2.         $(document).ready(function () {  
  3.             $.ajax({  
  4.                 type: "POST", url: "Index.aspx/GetCountriesName", dataType: "json", contentType: "application/json", success: function (res)  
  5.                 {  
  6.                     $.each(res.d, function (data, value) {  
  7.   
  8.                         $("#ddlNationality").append($("<option></option>").val(value.CountryId).html(value.CountryName));  
  9.                     })  
  10.                 }  
  11.   
  12.             });  
  13.   
  14.         })  
  15.           
  16.     </script>  

Now, see the output.