Bind DropDownList in Asp.Net Using JQuery

Then Add New a class as follows

public class clsDropDownList
{
public string DataValueField { get; set; }

public string DataTextField { get; set; }
}


we are using these class properties to set the DataTextField and DataValueField Of DropDownList

In Asp.Net Code Behind File Write this web Method

[WebMethod]
public
static List<clsDropDownList> PopulateCountriescls()
{

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
String strQuery = “select CountryID,CountryName from Country”;

var objList = (new[] { new { Text = “–Select–”, Value = 0 } }).ToList();

using
(SqlCommand cmd = new SqlCommand(strQuery, con))
{

//cmd.Parameters.AddWithValue(“@Name”, strName);

DataTable dt = new DataTable();

SqlDataAdapter da = new SqlDataAdapter(cmd);

con.Open();

da.Fill(dt);

con.Close();

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

for
(int i = 0; i < dt.Rows.Count; i++)
{

lst.Add(new clsDropDownList { DataValueField = Convert.ToString(dt.Rows[i]["CountryID"]), DataTextField =
Convert.ToString(dt.Rows[i]["CountryName"]) });

}

return
lst;
}

}

Add new demo.js file to your application and add following code

function BindDropDownListsByDictionarycls(MethodURL, json, DropDownID) {
$.ajax({
type: “POST”,

contentType: “application/json; charset=utf-8?,
data: ‘{}',

url: MethodURL,

dataType: “json”,

success: function (data) {

var
select = $(DropDownID);
select.children().remove();

select.append($(“<option>”).val(0).text(‘–Select–'));k

if
(data.d) {
$(data.d).each(function (index, item) {

select.append($(“<option>”).val(item.DataValueField).text(item.DataTextField));

});

}

},

error: function (XMLHttpRequest, textStatus, errorThrown) {

alert(textStatus);

alert(errorThrown);

}

});

Add Following Code in source file(.aspx file)

<script src=Script/Demo.js” type=”text/javascript”></script>

<script src="”http://code.jquery.com/jquery-1.9.1.js”" type="”text/javascript”"></script>
<
script src="”http://code.jquery.com/ui/1.10.2/jquery-ui.js”" type="”text/javascript”"></script>
<
div>

<table>
<tr
>

<td
>

Select Country:

</td
>

<td
>

<asp:dropdownlist id="”ddlcountry”" runat
="”server”">

</
asp:dropdownlist>
</td
>

</tr
>

<tr
>

<td
>

<input type="”button”" value="”Show”" id="”btnShow”"
/>

</td
>

</tr
>

</table
>

</
div>
<
script type="”text/javascript”">
$(document).ready(function () {

var obj = {};

obj["A"] = “0?;

var json = JSON.stringify(obj);

// FillDataset(“AutoCompleteDropDownList.aspx/PopulateCountries”, json, success);

// BindDropDownListsByDictionary(“AutoCompleteDropDownList.aspx/PopulateCountries”, json, “#ddlcountry”);

BindDropDownListsByDictionarycls(“AutoCompleteDropDownList.aspx/PopulateCountriescls”, json, “#ddlcountry”);

});

$(‘#btnShow').click(function () {

alert($(‘#ddlcountry').find(‘option:selected').val() + ‘:' + $(‘#ddlcountry').find(‘option:selected').text());

});

</
script>