[英]How to call C# server side function from Javascript in ASP.net
我在服務器端有一個函數可以填充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仍然為空。
請幫助我解決這個問題,我認為這是一個回發問題,因為當我調試代碼時, dropdownlist
項目已滿,但沒有顯示在下拉列表中。
謝謝
這將不起作用,如何進行設置。 您可以做一個更新面板,但這太過分了,IMO。 問題是您正在進行一次AJAX調用,該調用僅返回到服務器並返回到客戶端。 頁面以及控件永遠都不會回到服務器重新呈現。
相反,您需要將成功回調中的結果綁定到下拉列表。 因此,您的網絡方法需要更改:
[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]
多虧了這篇文章,您獲得了指導: 在客戶端javascript修改后獲取DropDownList的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.