You are not Logged in
Would you like to Login or Register

Today is: Friday, 05 September, 2008
Check this months hot topics

Returning a value from a PageMethod using MS AJAX

NOTE: This is designed for v1.0.61025.0 of AJAXExtensionsToolbox.dll

If you've ever returned data from a web service using MS AJAX this technique will look familar.

Call the method from javascript by append PageMethods. to the front of the method name. Add a delegate to the end of the method's parameters to get the result.

<script language="javascript" type="text/javascript">
    function MyMethod_Result(ResultString)
    {  
        alert(ResultString);
    }
    
    function CallMyMethod(){
        PageMethods.MyMethod("World", MyMethod_Result);
    }
</script>

I have made the source to this available to download, otherwise take a look at the full explanation below:

Full explanation - Step 1 - Enable Page Methods on your ScriptManager

Set the EnablePageMethods attribute to true

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

Step 2 - 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;
}

Step 3 - Call it from Javascript

Call the method from javascript by append PageMethods. to the front of the method name. Add a delegate to the end of the method's parameters to get the result.

<script language="javascript" type="text/javascript">
    function MyMethod_Result(ResultString)
    {  
        alert(ResultString);
    }
    
    function CallMyMethod(){
        PageMethods.MyMethod("World", MyMethod_Result);
    }
</script>
kick it on DotNetKicks.com del.icio.us digg Mister Wong YahooMyWeb Reddit Furl Spurl blogmarks
Paul Hayman Skype
Author : Paul Hayman
Published : Thursday, 26 July, 2007

Paul is the COO of kwiboo ltd consultant and has more than a decade of 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

diamond_king said:

very good solution thank man

June 23, 2008 - 10:34 AM

rajeep said:

Just what I was looking for !

thankyou

July 23, 2008 - 8:47 AM

Add Comment

Enter your comment below and it will be submitted for moderation.

Your Name

Add Tag

Please enter tags for this article, seperated by semi-colon ;

View Tag's by : # articles | # views