First create table as given below.
CREATE TABLE [dbo].[City](
[CityId] [int]
NOT NULL,
[CityName]
[nvarchar](50) NULL,
[StateId]
[int] NULL,
CONSTRAINT [PK_City] PRIMARY
KEY CLUSTERED
(
[CityId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS
= ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Then insert some dummy values into this table.
Put dropdown control on asp.net page.
<div>
<asp:DropDownList ID="ddlCustomers"
runat="server">
</asp:DropDownList>
</div>
Now write a code for PageBehind.
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.UI.MobileControls;
public partial class Jquery_BindDropdownUsingJquery
: System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
PopulateDropdown();
}
[System.Web.Services.WebMethod]
public static List<ListItem>
PopulateDropdown()
{
String strConnString = ConfigurationManager
.ConnectionStrings["test"].ConnectionString;
String strQuery = "select
CityId, CityName from City";
using (SqlConnection
con = new SqlConnection(strConnString))
{
using (SqlCommand
cmd = new SqlCommand())
{
List<ListItem>
list = new List<ListItem>();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
list.Add(new ListItem
{
Value=dr["CityId"].ToString(),
Text=dr["CityName"].ToString()
});
}
con.Close();
return list;
}
}
}
}
Now write JQuery code to populate dropdown value.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$.ajax({
type:"POST",
url: "BindDropdownUsingJquery.aspx/PopulateDropdown",
data:'{}',
contentType:"application/json; charset=utf-8",
dataType:"json",
success :function(r){
var ddlCustomers = $("[id*=ddlCustomers]");
ddlCustomers.empty().append('<option
selected="selected" value="0">Please
select</option>');
$.each(r.d,
function () {
ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
});
});
</script>
Please
run the code and check output.