2011-12-14 95 views
1

我有麻煩的ASP獲得選擇的值:DropDownList的。我正在使用AJAX並且想要動態更新Default.aspx頁面。這是行得通的,但是,從DropDownList中檢索的值沒有正確傳遞給ASP函數。的DropDownList的SelectedValue不工作

的ASP函數返回的東西,只是沒有一個字符串。我是否正確地做這件事?

的Default.aspx:

<script type="text/javascript"> 

    // Calls an ASP function, gets user surname 
    function GetData(){ 
     var response = UserForm.GetData(); 
     alert (response); // returns [object object] 
     document.getElementById("surnameLabel").innerHTM = response; 
    } 

</script> 

<asp:SqlDataSource 
    id="Users" 
    runat="server" 
    connectionstring="<%$ ConnectionStrings:ConnectionString %>" 
    selectcommand="select username, userid from users" 
> 
</asp:SqlDataSource> 

<asp:DropDownList 
    id="UserList" 
    name="UserList" 
    runat="server" 
    DataSourceID="Users" 
    DataTextField="username" 
    DataValueField="userid" 
> 
</asp:DropDownList> 

<input type="button" onclick="GetData();" value="Get Surname" /> 

<asp:Label name="surnameLabel" id="surnameLabel" Text="No user selected"></asp:Label> 

Default.aspx.cs:

public partial class UserForm : System.Web.UI.Page 
{ 

    protected void Page_Load(object sender, EventArgs e) 
    { 
    Ajax.Utility.RegisterTypeForAjax(typeof(AwardsForm)); 
    if (!this.IsPostBack) { } 
    } 

    // This function is called from the javascript function and looks up the users surname 
    [Ajax.AjaxMethod(HttpSessionStateRequirement.ReadWrite)] 
    public string GetData() 
    { 
     string userid = UserList.SelectedValue.ToString(); // this value keeps on equalling null 

     // Do some SQL using this ID to look up user surname 

     return Surname; 
    } 
} 

回答

1

基於您的代碼,看來你正在使用Ajax.Net。這是一個很長的時間,因爲我用這個庫,但我記得,無論是它不支持回發的控制值,或者你不得不調用其他設置或屬性的地方,使其工作。

無論如何,我認爲你將是關閉改變調用包含在方法調用中的選定值越好。

你應該能夠做這樣的事情:

var ddList = document.getElementById("UserList"); 
var response = UserForm.GetData(ddList.options[ddList.selectedIndex].value); 

更新

由於年齡和Ajax.net的明顯陳舊(在CodePlex上最後一次更新是在2006年),我會建議在您的頁面中使用靜態WebMethod來提供此功能。

這裏有變化,你應該:

1)導入System.Web.Services命名空間

using System.Web.Services; 

2)的用戶ID作爲參數轉換您的GetData方法靜態方法與WebMethod屬性裝飾:

[WebMethod] 
    public static string GetData(string sUserId) 
    { 
     // Do some SQL using this ID to look up user surname 

     return Surname; 
    } 

3)一個ScriptManager添加到您的網頁,或將其更改爲如下所示如果它已經存在:

<asp:ScriptManager ID="ScriptManager1" 
     runat="server" EnablePageMethods="true"> 
    </asp:ScriptManager> 

4)改變你的JavaScript調用這種新方法與新的參數:

var ddList = document.getElementById("UserList"); 
var response = PageMethods.GetData(ddList.options[ddList.selectedIndex].value); 

還有就是這this MSDN documentation一個很好的例子。

需要注意的是一些例子,包括一個在上面的鏈接,對劇本經理聲明和JavaScript調用的變化,但我沒有與任何那些經驗。

+0

對,你知道是否有更新的方法,人們用這種東西?我試圖將一個Javascript變量傳遞給ASP函數,但由於某種原因它不起作用。 所有我需要做的是動態的SQL查詢,只要值變回ASPX沒有一個總的刷新。 – 2011-12-15 03:32:54

相關問題