ASP.NET AJAX: Invoke a static method from script

Did you know that with ASP.NET AJAX you can easily invoke static methods declared on your ASP.NET page from script on the client?  To enable this you will need to do the following:

  1. Define the method you want invoked and make it static
  2. Add the System.Web.Services.WebServiceAttribute to the method
  3. Include the ASP.NET AJAX ScriptManager component to the web page and set the EnablePageMethods property to true

Once this is done, you can asynchronously invoke the static method by using the PageMethods proxy the ScriptManager adds to the page.  The following markup and code demonstrate this by using the classic AJAX example that retrieves the current time on the server.  Because the method is invoked asynchronously, you need to supply the callback javascript function that handles dealing with the return value.

View Demo

The example page below demonstrates this.  GetServerTime is the static method on the page that is decorated with the WebMethod attribute.  It returns the time on the server as a string.  The javascript function ScriptCallback is the callback that is called when the static method finishes executing. 

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    
    /// <summary>
    /// Static method that retrieves the time from the server
    /// </summary>
    /// <returns></returns>
    [System.Web.Services.WebMethod]
    public static string GetServerTime()
    {
        return DateTime.Now.ToString();
    }
    
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
        //  JavaScript callback that is invoked when
        //  the static method call returns
        function ScriptCallback(result)
        {
            $get('time').innerHTML = result;
        }
    </script>    
</head>
<body>
    <form id="form" runat="server">
        <asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true" />
        <div id="time">Click the Refresh button to view the server time</div>
        
        <%--HTML button that when clicked displays the time on the server--%>
        <input type="button" value="Refresh" onclick="PageMethods.GetServerTime(ScriptCallback);" />
    </form>
</body>
</html>

TrackBack

TrackBack URL for this entry:
http://mattberseth.com/blog-mt/mt-tb.fcgi/30

Listed below are links to weblogs that reference ASP.NET AJAX: Invoke a static method from script:

» ASP.NET AJAX: Invoke a static method from script from DotNetKicks.com
You've been kicked (a good thing) - Trackback from DotNetKicks.com [Read More]

Comments


Cool, looks simple.

Great blog.
Great info.

Posted by: Rafi on November 15, 2007 12:00 AM

Cool! and it works. I came across this after wasting several hours trying to get the AJAX toolkit dynamic updater to run asynchronously on load of the page. No... only on a click... aarggh!

This simple tip saved my day!

Posted by: prashant on December 15, 2007 12:00 AM

it gives me error.
i m new with ajax.
it gives me error that
Undefined

asp tag ScriptManager.
what i do

Posted by: JAIPRAKASH on December 20, 2007 12:00 AM

Very nice Tips

Posted by: Anonymous on February 7, 2008 12:00 AM

I get HTTP verb post not allowed when I do this. Any tips to get around

Page methods are a great way to implement AJAX.

The AJAX Control Toolkit provides a set of common components, but custom code is greatly simplified through the use of page methods in ASP.NET.

Posted by: ntulip on May 15, 2008 12:00 AM

ive followed your example and it seems that it doesnt work when your controls which expose the methods are all web controls inserted directly into a master page.

Any ideas if this was by design?

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

Consulting Services

Yep - I also offer consulting services. And heck, I'll do just about anything. If you enjoy my blog just drop me an email describing the work you need done.

Recent Comments

  • ntulip wrote: ive followed your example and it seems that it doesnt work when your controls which expose the metho...
  • Nitin Reddy wrote: Page methods are a great way to implement AJAX. The AJAX Control Toolkit provides a set of common c...
  • Anonymous wrote: I get HTTP verb post not allowed when I do this. Any tips to get around ...
  • JAIPRAKASH wrote: Very nice Tips ...
  • prashant wrote: it gives me error. i m new with ajax. it gives me error that Undefined asp tag ScriptManager. what ...
  • Rafi wrote: Cool! and it works. I came across this after wasting several hours trying to get the AJAX toolkit dy...
  • ASP.NET applications wrote: Great blog. Great info. ...
  • mel wrote: Cool, looks simple. ...