Calling Page Method [.AJAX]

In this blog post, we will learn how to call a method existing on a page using Ajax.
 
First of all, the method should have the WebMethod attribute and should be static.

        [System.Web.Services.WebMethod]
        public static string GetServerTime()
        {
            return DateTime.Now.ToString();
        }
The above method will return the date time on the server.

Second, You should add the EnablePageMethods="true" attribute to the ScriptManager control to allow calling a page method.

Now on client pageload event we will call the method on the server which will return a string containing the date time and display it on a textbox inside an UpdatePanel Control

        <script language="javascript">
        function pageLoad(sender, eventArgs)
        {
    
            getTime();
        }
        function getTime()
        {
            // call the method on the server and wait till the code has completed its execution
            PageMethods.GetServerTime(OnGetServerTimeComplete)
        }
        function OnGetServerTimeComplete(result, userContext, methodName)
        {  
            // Get the textbox inside the UpdatePanel Control
            var textbox = $get('<%=txtDateTime.ClientID%>');
            // Set the result into the textbox
            textbox.value = result;
        }
        </script>

Hope this Helps,

Comments

# re: Calling Page Method [.AJAX]

Tuesday, September 04, 2007 12:50 PM by BasharKokash

Thanks alot.

Could you please give more details about the paramerters passed to to the OnGetServerTimeComplete function.

# re: Calling Page Method [.AJAX]

Tuesday, September 04, 2007 1:19 PM by haissam

You can send the parameter to the server side function before the OnGetServerTimeComplete parameter. example below

PageMethods.GetServerTime('Testing',OnGetServerTimeComplete)

Now the word Testing will be send to the GetServerTime server side function

HC

# re: Calling Page Method [.AJAX]

Wednesday, September 26, 2007 3:53 PM by Mike

Can you have user control with page method and ajax control so you can reuse it? Or only pagemethod of the page control on will be called?

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.