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>