2009-07-27 53 views
0

我见过很多相关的问题,但我找不到一个简单的代码示例,通过jquery将参数传递回页面方法。ASP.NET窗体:使用jquery发布到带有参数的asp.net页面方法

我查看了一些在encosia.com上的例子(谢谢,戴夫),但仍然没有设法让它工作。以下代码到目前为止:

更新 - 添加了一些代码传递参数,但它仍然无法正常工作。

Test.aspx文件:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title>test page</title> 

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 

    <script type="text/javascript"> 
     $(document).ready(function() { 
     // Add the page method call as an onclick handler for the div. 
     $("#Result").click(function() { 
      var intxt = document.getElementById("<%= txtIn.ClientID %>").value; 
      var params = $.toJSON({ 'inStr': intxt }); 
      $.ajax({ 
      type: "POST", 
      url: "test.aspx/RunTest", 
      data: params, 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function(msg) { 
       $("#Result").text(msg); 
      } 
     }); 
     }); 
     }); 
    </script> 

</head> 
<body> 
    <form id="form1" runat="server"> 
    <div id="Result">Click here</div> 
    <asp:TextBox ID="txtIn" runat="server"></asp:TextBox> 
    </form> 
</body> 
</html> 

和test.aspx.vb:

<WebMethod()> _ 
    Public Shared Function RunTest(ByVal instr As String) As String 
     Return "this is your string: " + instr 
    End Function 

更新:

在上面的runTest menthod永远不会被调用。但是,如果我也有:

<WebMethod()> _ 
    Public Shared Function RunTest() As String 
     Return "no params here" 
    End Function 

然后第二个方法被调用。

我错过了什么?这是错误的方法?

回答

2

参数区分大小写。你

var params = $.toJSON({ 'inStr': intxt }); 

不匹配方法签名:

Public Shared Function RunTest(ByVal instr As String) As String 

它的其余部分看起来是正确的。

我通常会建议using json2.js' JSON.stringify() to serialize JSON on the client-side,而不是其他插件,如$ .toJSON。 json2.js的API与新的浏览器正在实现的浏览器原生JSON支持(目前为IE8和Fx3.5)的ECMA标准相匹配。因此,如果您使用JSON.stringify()来序列化对象,它将自动升级到这些浏览器中更快,本地化的功能。

+0

感谢@Dave Ward,我也试图解决这个问题,并在使params区分大小写之后解决了问题。非常感谢!。 – 2012-03-23 11:34:07

相关问题