2015-04-28 49 views
0

我在服务器端有一个填充dropdownlist的函数。我打电话跟客户端的按钮,这个功能在Javascript与PageMethods点击这样的:如何在ASP.net中用Javascript调用带客户端副作用的C#服务器端函数

<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仍为空。

所以请帮助我解决这个问题,我认为这是后背部有问题的,因为当我调试代码,items of dropdownlist are full but don't show that.

谢谢

+0

所以你越来越“一切都好!”作为回应,但下拉仍然是空的,是吗? –

+0

你在哪里绑定了'dropdownlist'? – BNN

+0

是@HarveySpecter –

回答

3

这样可不行,你怎么把它设置。你可以做一个更新面板,但这将是矫枉过正,国际海事组织。问题是你正在做一个AJAX调用,它只返回到服务器并返回到客户端。该页面以及控件从不返回到服务器以重新呈现。

相反,您需要将onsuccess回调的结果绑定到您的下拉列表。所以,你的Web方法需要改变:

[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

+0

我的大问题是我想处理它在服务器端功能:( –

+1

将任何回发的结果能够看到列表中的这些动态条目?从我记得,如果他们不在那么你不能在服务器端对它们做任何事情,如果页面当然不会发布数据,那么这不是问题 – Klors

+0

好的,所以你真的想使用更新面板,然后 – JasonWilczak

相关问题