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,

Published 31 August 2007 10:21 AM by haissam

Comments

# BasharKokash said on 04 September, 2007 12:50 PM

Thanks alot.

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

# haissam said on 04 September, 2007 01:19 PM

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

# Mike said on 26 September, 2007 03:53 PM

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?

# Alex said on 24 December, 2009 03:07 AM

But howto call without System.Web.Services.WebMethod????

This site

Search

Go

This Blog

Syndication

Sponsors

  • MaximumASP
  • Breaking News
  • Find a Job
  • Social Bookmarking
    Tidebuy Reviews
    Online Shopping
    asp.net hosting
    UK online local dating