Monday, June 17, 2013

How to fill dropdownlist by Jquery Ajax?

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Filldropdownbyjquery2.aspx.cs" Inherits="Filldropdownbyjquery2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<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: "Filldropdownbyjquery2.aspx/BindDatatoDropdown",

data: "{}",

dataType: "json",

success: function (data) {

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

$("#ddlCountry").append($("<option></option>").val(value.CustomerId).html(value.Country));



});

},

error: function (result) {

alert("Error");



}

});

});

</script>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:DropDownList ID="ddlCountry" runat="server"></asp:DropDownList>





</div>

</form>

</body>

</html>


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

using System.Web.Services;

public partial class Filldropdownbyjquery2 : System.Web.UI.Page



{
 
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=Abhishek-pc\sql2008;Initial Catalog=Test_DB;integrated security=true"))



{
 
using (SqlCommand cmd = new SqlCommand("SELECT top 500 CustomerId,Country FROM Customer order by Country desc", con))



{

con.Open();
 
SqlDataAdapter da = new SqlDataAdapter(cmd);



da.Fill(dt);
 
foreach (DataRow dtrow in dt.Rows)



{
 
CountryDetails country = new CountryDetails();

country.CustomerId = Convert.ToInt32(dtrow["CustomerId"].ToString());

country.Country = dtrow["Country"].ToString();



details.Add(country);

}

}

}
 
return details.ToArray();



}
 
public class CountryDetails



{
 
public int CustomerId { get; set; }

public string Country { get; set; }



}

}
 
 

No comments:

Post a Comment