Jquery – ASP.NET Forms: Using jquery to post to asp.net page method with parameters

asp.netjquerypagemethodswebforms

I've seen lots of related questions, but nowhere have I found a simple example of code that passes parameters back to a page method via jquery.

I've looked through some of the examples at encosia.com (thanks, Dave) but still haven't managed to get it working. Here's the code so far:

Updated – added some code to pass in params, but it's still not working.

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>

and in test.aspx.vb:

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

Update:

The RunTest menthod above is never called. However, if I also have:

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

Then the 2nd method IS called.

What am I missing? Is this the wrong approach?

Best Solution

The parameters are case sensitive. Your

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

Doesn't match the method signature:

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

The rest of it looks correct.

I would generally suggest using json2.js' JSON.stringify() to serialize JSON on the client-side, instead of other plugins like $.toJSON. json2.js' API matches the ECMA standard for browser-native JSON support which newer browsers are implementing (IE8 and Fx3.5 so far). So, if you're using JSON.stringify() to serialize your objects, it will automatically upgrade to the faster, native functionality in those browsers.