2015-04-28 48 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

相關問題