2011-12-14 92 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

相关问题