我正在尝试使用 Ajax 填充 DropDownList。我的代码如下。我已经单步执行了所有代码,一切正常,没有任何明显的 C# 或 Jquery 错误。单击按钮,Jquery 运行并调用我的 WebMethod。我的 C# 代码中命中了 GetLanguageList 断点,并成功返回 6 个对象的列表。 success 函数迭代 6 个对象中的每一个。但是,下拉列表仍然为空。我没有使用更新面板。
我尝试将返回类型更改为ListItem 的数组和列表。我尝试使用 AjaxControlToolkit ComboBox 而不是 DropDownList。我尝试过在文档就绪时而不是在按钮单击时填充 DropDownList。我确实将 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']));
});
}
关于javascript - 无法使用 Ajax 填充 DropDownList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32148649/