0

Bind dropdown using JQuery Ajax

Here I am going to explain how to bind dropdown using JQuery Ajax. Follow my steps.

Step 1:- Add one web .aspx web page to your asp.net application.

Step 2:- Create a class CountryList with the following properties.

public class CountryList

{

public int CountryId { get; set; }

public string CountryName { get; set; }

}

Step 3:- Create a Static method to return data to Ajax call. As I created a List of CountryList to add CountryId and CountryName.

Notes:- 1. Method should be a static .

  1. Method should be a WebMethod.
  2. WebMethod is available inside System.Web.Services namespace.

[WebMethod]

public static List<CountryList> GetCountriesName()

{

List<CountryList> lst = new List<CountryList>();

lst.Add(new CountryList() { CountryId=1,CountryName=”India”});

lst.Add(new CountryList() { CountryId = 2, CountryName = “Nepal” });

lst.Add(new CountryList() { CountryId = 3, CountryName = “America” });

return lst;

 

}

Step 4:- Now it is time to write JQuery,Ajax code.

4.1 Add JQuery script to Your head section of .aspx page

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

4.2 Create a dropdown menu to bind data.

<select id=”ddlNationality”><option value=”0″ >–Select Country–</option></select>

4.3 Write JQuery ,Ajax to call WebMethod(GetCountriesName) and bind retuning data to dropdown.

<script type=”text/javascript”>

$(document).ready(function () {

$.ajax({

type: “POST”, url: “Index.aspx/GetCountriesName”, dataType: “json”, contentType: “application/json”, success: function (res)

{

$.each(res.d, function (data, value) {

 

$(“#ddlNationality”).append($(“<option></option>”).val(value.CountryId).html(value.CountryName));

})

}

 

});

 

})

 

</script>

4.3 Now see the output.

Admin

Leave a Reply

Your email address will not be published. Required fields are marked *