Bind dropdownlist in asp.net using jquery with JSON

Introduction:
This article explains how to bind dropdownlist using JQuery ajax or JSON in asp.net. To implement this concept first design table in database and give name as Country as shown below.
Bind dropdownlist in asp.net using jquery with JSON
After completion table design enter some of Country details in database to work for our sample and write the following code in your aspx page

HTML Code-

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Bind Dropdownlist with JQuery in asp.net</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/
jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/BindDatatoDropdown",
data: "{}",
dataType: "json",
success: function(data) {
$.each(data.d, function(key, value) {
$("#ddlCountry").append($("<option></option>").val(value.CountryId).html(value.CountryName));
});
},
error: function(result) {
alert("Error");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlCountry" runat="server" />
</div>
</form>
</body>
</html>

C# Code-

protected void Page_Load(object sender, EventArgs e)
{

}
[WebMethod]
public static CountryDetails[] BindDatatoDropdown()
{
DataTable dt = new DataTable();
List<CountryDetails> details = new List<CountryDetails>();

using (SqlConnection con = new SqlConnection("Data Source=Vepsh;Initial Catalog=SampleDB;
Integrated Security=true"))
{
using (SqlCommand cmd = new SqlCommand("SELECT CountryID,CountryName FROM Country", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
CountryDetails country = new CountryDetails();
country.CountryId = Convert.ToInt32(dtrow["CountryId"].ToString());
country.CountryName = dtrow["CountryName"].ToString();
details.Add(country);
}
}
}
return details.ToArray();
}
public class CountryDetails
{
public int CountryId { get; set; }
public string CountryName { get; set; }
}


Ashwani
Ashwani

This is a short biography of the post author. Maecenas nec odio et ante tincidunt tempus donec vitae sapien ut libero venenatis faucibus nullam quis ante maecenas nec odio et ante tincidunt tempus donec.

1 comment: