Calling a static "page method" from Javascript using MS AJAX

Atlas gave us the ability to easily call Web Services from JavaScript. MS AJAX has gone one step further! We can now call methods in the codebehine of the current page from Javascript. Here's how:

This is designed for v1.0.61025.0 of AJAXExtensionsToolbox.dll

Enable Page Methods on your ScriptManager

Set the EnablePageMethods attribute to true

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

Mark your method as static and give it the WebMethod attribute

The method has to be declared static. It must also be marked with the WebMethod attribute. You'll probably find that you need to include System.Web.Services

using System.Web.Services;
[WebMethod]
public static string MyMethod(string name)
{
    return "Hello " + name;
}

Call it from Javascript

To call the method from javascript you need to append PageMethods. to the front of the method name.

<script>
    function test(){
        alert(PageMethods.MyMethod("Paul Hayman"));
    }
</script>
Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.

Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.

Comments

Anastasiosyal said:

This is cool! What about security? If you needed to be logged in to execute "MyMethod", does the xmlhttpRequest issued contain a session cookie with it?

11/Jul/2007 14:07 PM

phayman said:

This is something I considered myself.. what I decided to do in my implementation was check that the user was in one of the allowed rolegroups for the operation.

To clarify, I used this for passing back information from a content editor. So, a check to see if the user was an Administrator or Editor was sufficient.

Paul

11/Jul/2007 14:14 PM

Wouter said:

Hi, I get an exception "PageMethods is not defined". Any ideas? is PageMethods an internal js object or am I missing something?

26/Jul/2007 09:59 AM

phayman said:

After discussing it with Wouter we discovered that his problem was caused by the WebMethod being located inside a UserControl, not the Page.

It would appear that you can't call a WebMethod located in a UserControl.

If anyone knows how to achieve this, post a comment.

Paul

26/Jul/2007 10:51 AM

Andres V said:

I'm able to hit the server method, but it is returning me "undefined" instead of the string "Hello whatever".

What am I doing wrong?

17/Aug/2007 23:04 PM

Nelero said:

I'm facing with the same problem as Andres V. When I call my webservice method, returning a string, i get "undefined"...

27/Aug/2007 18:37 PM

Gerard van de Ven said:

Yes, the actual way of doing this is to use a "onComplete" because of the asynchronous call, as follows:

  <script type="text/javascript">

    function test(){

        PageMethods.MyMethod("Gerard van de Ven", OnMyMethodComplete);

    }



    function OnMyMethodComplete(result, userContext, methodName)

    {

      alert(result);

    }

  </script>

02/Oct/2007 21:20 PM

nik said:

excellent, thanks

31/Mar/2008 15:14 PM

phayman said:

Not marking the PageMethod as STATIC is quite a common mistake, be sure to mark your metdod as STATIC

31/Mar/2008 15:54 PM

lkeel said:

I am having a problem calling my webmethod from javascript. Everything was working fine until I implemented security. Now when I do PageMethod.TestCall("something"); I get a 401 - Authentication Error. Do you have any ideas on how to resolve this problem?

29/May/2008 17:41 PM

Lkeel said:

I am trying to make a call back to my server from the javascript the same as you have here. My problem is that now that I have secured my website with forms authentication, the call back to the server is throwing a 401-Authentication error. Have you seen this before? Do you have a work around for this problem?

02/Jun/2008 15:06 PM

rajeep said:

just what i was looking for thanks

23/Jul/2008 08:47 AM

Sqeeb said:

Having problems here....

I'm using the same code verbadum (enabling scriptManager page methods, your javaScript and codebehind method) on a master page. For some reason, it's not liking PageMethods and won't call the server side function. Any Suggestions?

21/Aug/2008 18:53 PM

Gerro said:

Excellent. Works for me as is in the orignal post. (not using security).

11/Jun/2009 15:06 PM

kalpana said:

Excellent,it's working fine after Enabling pagemethods in script manager.Thank's for the post.

24/Aug/2009 08:26 AM

Deepa Sehgal said:

its realy helpful for me but you havn't explained why it is necessary to make static methods and what is the purpose of writing WebMethod

10/Dec/2009 17:06 PM

Iti Sharma said:

I tried using both above mentioned methods but none of them worked. If, I write <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true" /> , then page doesn't load. Otherwise, it is executing javascript but not calling PageMethods.

Please tell me any solution.

11/Dec/2009 06:47 AM

fsanchez said:

Hello...I have the same problem as Sqeeb ... using Master Page it seem not works

08/Jan/2010 18:14 PM

TheXenocide said:

@phayman - ASP.NET AJAX does not facilitate a means to use static WebMethods in UserControls but I too have been very interested in this (mostly for the sake of encapsulating my control's logic within my control's class). Since there was no solution I set out to find a way to do it, which I've just recently finished. There's not much documentation on my solution yet, but if you want to take a peak I'd be interested in your thoughts.

I've written a post about my attempts here: http://xeno.extendev.org/2010/01/control-methods-for-aspnet-ajax.html

And you can get the source code/samples here: http://controlmethods.codeplex.com/

19/Jan/2010 14:53 PM

pavan alluri said:

i was trying to implement the same functionality in VB.net but it was throwing an error saying "Microsoft JScript runtime error: 'PageMethods' is undefined"

24/Jun/2010 12:59 PM

Rashid Mehmood said:

Thanks Excellent

19/Mar/2011 10:25 AM

Jitendra said:

I did same way, you have done .but it is not working .Kindly give me the solution.

15/Jun/2011 09:20 AM

anisha said:

i want to use same code for my master page bt it is giving error as page methods not define...please give me the code as soon as possible....

02/Dec/2011 07:14 AM

Phong_Van89 said:

This is cool! Thank you very much. it is great!

07/Dec/2011 04:11 AM

better said:

why webmethod not run on iis?can you help me fix it? thank you very much

08/Dec/2011 12:52 PM

Ismail said:

Thanks, it helps us.

02/Jul/2012 10:05 AM

Shailesh said:

Thanks to all

07/Sep/2012 10:09 AM

RogerDodge said:

Useful reference here - thanks

I need access to the Session object in the WebMethod and needed to add the following decoration to the method

[System.Web.Services.WebMethod(EnableSession=true)]

May help someone

10/Oct/2012 14:58 PM

Nehal said:

Thanks.. gd stuff!!

05/Nov/2012 10:56 AM

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.