Welcome to MSDN Blogs Sign in | Join | Help

Syndication

News

PageMethods in ASP.Net AJAX 1.0 RC
Since it was surprisingly difficult to find sample code, I decided to kick off my first post with a little bit about PageMethod's in ASP.Net AJAX 1.0 RC. A PageMethod is basically just a method that is exposed and callable from client script. The method must be defined as a public static and can be located in the aspx page or in the code behind (in the beta it could not be in the code behind).
public partial class _Default : System.Web.UI.Page
{
   [System.Web.Services.WebMethod]
   [System.Web.Script.Services.ScriptMethod]
   public static string ReverseString(string data)
   {
      if (data == null || data.Length == 0)
         throw new ArgumentNullException("data", "data param can not be null or empty string");

      char[] reversed = new char[data.Length];
      for (int i = 0, j=data.Length- 1; i < data.Length; i++, j--)
      {
         reversed[i] = data[j];
      }

      return new string(reversed);
   }
}

To then call the method via client script you would use the PageMethods object and using the method name as defined in the page class, like PageMethods.ReverseString("some string").

<body>
   <script type="text/javascript" language="javascript">
      function ReverseString()
      {
         var control = $get("InputString");
         PageMethods.ReverseString(control.value, ReverseSucceeded, ReverseFailed, control);
      }

      function ReverseSucceeded(results, ctl)
      {
         ctl.value = results;
      }

      function ReverseFailed(results, ctl)
      {
         alert(results.get_message());
      }

   </script>

   <form id="form1" runat="server">
      <asp:ScriptManager ID="ScriptManager1" runat="server" />

      <asp:TextBox ID="InputString" runat="server" />
      <asp:Button ID="ReverseIt" runat="server" OnClientClick="ReverseString(); return false;" />
   </form>
</body>

When calling the method, the first <n> parameters in the PageMethods call match the parameters to the class method. In this case its only one parameter, the string to be reversed. Optionally, the next parameter is the callback for success, followed by the callback for failure. Then is the context data, in this case I'm just sending the input control but it can be anything.

If you are curious about what happens next, here is some key info from Fiddler about the HTTP Request and Response.

The request looks like this minus some of the standard http stuff:

POST /AJAXCTPTest/Default.aspx/ReverseString HTTP/1.1
Referer: http://localhost:36993/AJAXCTPTest/Default.aspx
Content-Type: application/json; charset=utf-8
Host: localhost:36993
Content-Length: 37

{"data":"See the four horsemen ride"}

And the response:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 28

"edir nemesroh ruof eht eeS"

As you can see, PageMethods are pretty light and extremely easy to implement. I hope this helps save the next person a few minutes of searching.

Published Friday, January 05, 2007 11:08 PM by RobJ

Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: PageMethods in ASP.Net AJAX 1.0 RC @ Tuesday, January 09, 2007 8:49 AM

i agree, pagemethods are hardly documented, nice that you compiled here a quick sample.

i do not understand this line:

var control = $get("InputString");

what is the $-thing doin?

thanks

thomas

# re: PageMethods in ASP.Net AJAX 1.0 RC @ Tuesday, January 09, 2007 12:25 PM

$get() is just a utility method in the ajax client library. It's a shortcut to do something like document.GetElementById("InputString")

Here's a link to the docs on it:

http://ajax.asp.net/docs/ClientReference/Sys.UI/DomElementClass/a7caa926-929d-424c-8666-4d281c28271d.aspx#ID0EI6AG

RobJ

# PageMethods and Masterpage @ Wednesday, January 10, 2007 3:06 AM

Hello!

I don't get this working with Masterpages. (Contentpage include the JS and call the serverside PageMethode, in the Contentpage-Codebehind is the "Function" located, Scriptmanager is on the Masterpage)

Error: JS-Error on the Client: PageMethods is not definied!

Any experience with that?

Undying

# re: PageMethods in ASP.Net AJAX 1.0 RC @ Wednesday, January 10, 2007 7:25 PM

If I understand you correctly. I do have exactly that scenario on some code I'm working on now. MasterPage contains the ScriptManager, Aspx Code-Behind has the PageMethod and the Aspx page has the javascript.

1. Are you running the current RC version of Ajax or the Beta. In the beta, the method could not be in the codebehind, it could only be inline on the aspx page

2. Is the method public static? And decorated with [WebMethod] and [ScriptMethod] attributes?

Those are the most causes I've seen for that error.

RobJ

# re: PageMethods in ASP.Net AJAX 1.0 RC @ Tuesday, June 19, 2007 8:19 AM

I have a method called abandon session in my masterpage.cs which i'm calling from client script as PageMethods.AbandonSession()

That web method definition is there in master.cs which has HttpContext.Current.Session.Abandon();

method to call session_end in global.asax

But that event is not fired even after calling it.

Y this is not working i'm unable to understand please help me out.

bhanu

# re: PageMethods in ASP.Net AJAX 1.0 RC @ Thursday, June 21, 2007 3:39 AM

Thanks for this. I couldn't get it working for ages until I noticed that I needed to add EnablePageMethods="true" to the ScriptManager.

Indy

# re: PageMethods in ASP.Net AJAX 1.0 RC @ Thursday, June 21, 2007 9:57 AM

Thanks for the details you put together. It helped me to make PageMethods work. I have very different scenario. When I call a page method, it returns an error message as a string. Based on that in my Complete method I'll popup a Confirm box. And based on this Confirm box input of user I should either proceed further or stop processing. I have tried returning a bollean from my Complete method but that did not work.

I'm attaching the code I'm using here

<script language="javascript" type="text/javascript">

function WarnDuplicateName()

   {

      PageMethods.IsFirstAndLastNameExist(OnCallComplete, OnCallFailed);

      alert("call");

   }

   function OnCallComplete(errorMsg, isExist, methodName)

   {

       var userInput=false;

       if (errorMsg != null)

       {

           if(errorMsg != "")

               userInput = confirm(errorMsg);            

       }

       alert(userInput);

       return userInput;

   }

   function OnCallFailed(error, isExist, methodName)

   {

       if(error !== null)

       {

       }

   }

   </script>

-------------------------------------------

my aspx page calls JS function like this.

<asp:Button ID="btnSubmit" runat="server"                                    TabIndex="320" OnClientClick="return WarnDuplicateName();"/>

Siddarth

# re: PageMethods in ASP.Net AJAX 1.0 RC @ Wednesday, July 18, 2007 6:33 AM

This article is very fine,in this we are calling parameters but how to call a class.

kiran

# re: PageMethods in ASP.Net AJAX 1.0 RC @ Wednesday, August 29, 2007 9:38 PM

You are the man! i spent so much time trying to find this solution. Thank you so much!!!!!!

ds

# re: PageMethods in ASP.Net AJAX 1.0 RC @ Friday, September 21, 2007 1:28 PM

How can I reference a web control on my page in the Server side method:

public static string ReverseString(string data)

{

 TextBox1.Text = "some value";

}

officialboss

# re: PageMethods in ASP.Net AJAX 1.0 RC @ Tuesday, September 16, 2008 6:49 PM

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

should be the declaration for scriptmanager..

Mani

# re: PageMethods in ASP.Net AJAX 1.0 RC @ Monday, October 06, 2008 10:33 AM

weel done; concise and powerful

da

# See the Four horsemen ride @ Friday, February 06, 2009 12:34 PM

interesting code you chose to display in the http response, any meaning to it, or do u just like the sound of apocalyptic language

david

# re: PageMethods in ASP.Net AJAX 1.0 RC @ Thursday, May 28, 2009 3:34 AM

IS there Any limitaion of pagemethods,

like lilitation in data transfer from server side to client side.

V.K.SHARMA

# re: PageMethods in ASP.Net AJAX 1.0 RC @ Friday, October 16, 2009 8:27 AM

This summary is clear, to the point and simple.  Thank you for taking the time to do this.

Helene

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement  
Page view tracker