我在服务器端有一个函数填充dropdownlist
。我在Javascript中使用PageMethods
在客户端点击按钮来调用此函数,如下所示:
<asp:ScriptManager ID="smMain" runat="server" EnablePageMethods="true" />
<asp:Button runat="server" ID="SearchButton" Text="Search" OnClientClick="SearchButtonClick();return false;"/>
<asp:DropDownList runat="server" ID="SearchCityDropDownList" Width="100px"/>
和
function SearchButtonClick() {
PageMethods.SearchSearchButtonActivity(onSucess, onError);
}
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
服务器端功能:
[WebMethod]
public static string SearchButtonActivity()
{
string result = "Everything is OK!";
foreach (string value in getCityList())
{
SearchCityDropDownList.Items.Add(new ListItem(value));
}
return result;
}
当我运行此代码并单击按钮时,它只显示"Everything is OK!"
警报和
下拉列表仍为空。
请帮我解决这个问题,我认为这是一个回发问题,因为当我调试代码时,dropdownlist
的项目已满,但它们没有显示在下拉列表中。
谢谢
答案 0 :(得分:3)
这不起作用,如何设置。你可以做一个更新面板,但那将是矫枉过正的,IMO。问题是您正在进行AJAX调用,该调用只返回服务器并返回到客户端。该页面以及控件永远不会返回到服务器以进行重新渲染。
相反,您需要将onsuccess回调的结果绑定到下拉列表。所以你的网络方法需要改变:
[WebMethod]
public static string SearchButtonActivity()
{
var result = new List<string>();
foreach (string value in getCityList())
{
result.Add(value);
}
return result;
}
然后你的onSuccess客户端回调需要处理它:
function SearchButtonClick() {
PageMethods.SearchSearchButtonActivity(onSucess, onError);
}
function onSucess(result) {
SearchCityDropDownList.options.length = 0;
for (var i==0;i<result.length;i++) {
AddOption(result[i], i);
}
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
function AddOption(text, value) {
var option = document.createElement('option');
option.value = value;
option.innerHTML = text;
SearchCityDropDownList.options.add(option);
}
您可以这种方式检索所选的值,服务器端:
string selectedVal = Request[SearchCityDropDownList.UniqueID]
感谢此帖子的指导:Getting the value of a DropDownList after client side javascript modification