<script type = "text/javascript">
var ddlCountries;
function GetCountries() {
ddlCountries = document.getElementById("<%=ddlCountries.ClientID %>");
ddlCountries.options.length == 0;
AddOption("Loading", "0");
PageMethods.GetCountries(OnSuccess);
}
window.onload = GetCountries;
function OnSuccess(response) {
ddlCountries.options.length = 0;
AddOption("Please select", "0");
for (var i in response) {
AddOption(response[i].Name, response[i].value);
}
}
function AddOption(text, value) {
var option = document.createElement('<option value="' + value + '">');
ddlCountries.options.add(option);
option.innerText = text;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods = "true">
</asp:ScriptManager>
<div>
<asp:DropDownList ID="ddlCountries" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>
[System.Web.Services.WebMethod]
public static List<Country> GetCountries()
{
SqlConnection conn;
string constr = "Initial Catalog=" ";
conn = new SqlConnection();
conn.ConnectionString = constr; Session["Constr"].ToString();
conn.Open();
string sql = "Select distinct city from LOCATION";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[]
{
(dt.Rows.Count - 1)};
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["city"].ToString(), i);
i++;
}
return items;
}
public class Country
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private string _id;
public string Id
{
get { return _id; }
set { _id = value; }
}
}