无法使用Ajax填充DropDownList
问题描述:
我正在尝试使用Ajax填充DropDownList。我的代码如下。我已经介绍了所有的代码,并且所有的东西都没有任何明显的C#或Jquery错误。在按钮上点击Jquery运行并调用我的WebMethod。 GetLanguageList断点在我的C#代码中被击中,并且6个对象的列表被成功返回。成功函数遍历6个对象中的每一个。但是,下拉列表保持空白。我没有使用更新面板。无法使用Ajax填充DropDownList
我试着改变返回类型为数组和listItem列表。我试过使用AjaxControlToolkit组合框代替DropDownList。我试着让DropDownList填充到documentready上,而不是点击按钮。我修改了Text和Value到DropDownList的DataText和DataValue属性。
还有什么可能导致DropDownList不填充?
我的方法
[WebMethod()]
public static ArrayList GetLanguageList()
{
ArrayList lstArrLanguage = new ArrayList();
lstArrLanguage.Add(new ListItem("C#", "C#"));
lstArrLanguage.Add(new ListItem("Java", "Java"));
lstArrLanguage.Add(new ListItem("PHP", "PHP"));
lstArrLanguage.Add(new ListItem("VB.NET", "VB.NET"));
lstArrLanguage.Add(new ListItem("JavaScript", "JavaScript"));
lstArrLanguage.Add(new ListItem("jQuery", "jQuery"));
return lstArrLanguage;
}
我的Jquery
<script language="javascript" type="text/javascript">
$(function() {
$("#locationList").change(function() {
TestMethod();
}).change();
});
function TestMethod() {
$.ajax({
type: "POST",
url: '<%= ResolveUrl("EmailEditor.aspx/GetLanguageList") %>',
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#DropDownList1").empty().append($("<option></option>").val("[-]").html("Please select"));
$.each(msg.d, function() {
$("#DropDownList1").append($("<option></option>").val(this['Value']).html(this['Text']));
});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
};
</script>
<asp:Button ID="Button1" OnClientClick="TestMethod()" runat="server" Text="Button" />
<asp:DropDownList ID="DropDownList1" runat="server">
答
尝试更改成功函数如下:
success: function(msg) {
$("#<%= DropDownList1.ClientID %>").empty().append($("<option></option>").val("[-]").html("Please select"));
$.each(msg.d, function() {
$("#<%= DropDownList1.ClientID %").append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
+0
感谢您的提示。我一定要疯了才会错过。 – TimidObserver
你可以验证的ASP DropDownList控件的ID是事实上“DropDownList1”页面呈现时?根据我的经验,asp控件呈现的id与您指定的id相似,但不完全相同。你可能需要使用$('[id * =“DropDownList1”]')来定位元素。 –
使用'$('#')'引用下拉ID。当你调用WebMethod并在代码后面使用断点时,它在这里停止? –
您应该考虑重构$ .ajax调用来使用promises而不是配置参数。请参阅文档以获取使用示例。 从jQuery的网站:弃用声明:自jQuery 1.8起,弃用jqXHR.success(),jqXHR.error()和jqXHR.complete()回调。要准备代码以便最终删除它们,请改用jqXHR.done(),jqXHR.fail()和jqXHR.always()。来源:http://api.jquery.com/jquery.ajax/ –