我从JavaScript函数调用web方法
function loadstatecity() {
alert(document.getElementById("CountryList").value);
// PageMethods.username_availability(document.getElementById("CountryList").value, OnSuccess, OnFailure);
PageMethods.loadstatecity(document.getElementById("CountryList").value, OnSuccess,OnFailure);
}
Web方法返回一个字符串列表:
[System.Web.Services.WebMethod]
public static List<string> loadstatecity(string countrycode)
{
utilityFunc.loadstatecity(countrycode);
return utilityFunc.state;
}
loadstatecity功能代码:
public static void loadstatecity(string CountryCode)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mag_SDK"].ConnectionString))
{
con.Open();
using (SqlCommand com = con.CreateCommand())
{
com.CommandText = "Select ProvinceName from Province where CountryCode=@Country ;";
com.Parameters.AddWithValue("@country", CountryCode);
SqlDataReader dr = com.ExecuteReader();
while (!dr.Read())
{
state.Add(dr["ProvinceName"].ToString());
}
com.Connection.Close();
com.Connection.Dispose();
}
con.Close();
}
}
现在我想将此列表绑定到DropDownList。
我该怎么做?
感谢您的帮助。
答案 0 :(得分:0)
C#方法中返回的字符串类型列表将被序列化为JavaScript数组,并且可以在JavaScript回调中访问。然后,您需要遍历序列化数组中的所有字符串,将每个字符串转换为HTML“option”元素,然后将每个元素附加到ASP.NET生成的HTML“state”select元素。这里有一些应该实现的代码:
// The function to run on success, adds options to the state select.
function success(response) {
var select = document.getElementById('id-of-your-state-select-element'),
index = 0,
option = ''
value = '';
if (select) {
for (index; index < response.length; index++) {
value = response[index];
option = '<option>' + value + '</option>';
select.insertAdjacentHTML('beforeend', option);
}
}
}
// Shows an error in an alert box, should be improved before
// production deployment.
function error(response) {
alert(response);
}
然后在'loadstatecity'方法中将这两个函数用作成功/失败回调。
PageMethods.loadstatecity(document.getElementById("CountryList").value, success, error);