views:

1030

answers:

4

I have a very simple call to a PageMethod. When I step through my PageMethod in my .cs file, the value looks as expected. However, on the client side I get an undefined result. Any ideas? This should be horribly simple.

Here is my js: (EnablePageMethods="true" in my ASPX page)

function test() {
    alert(PageMethods.MyMethod("Joe Blow"));
}

And here is my C#:

public partial class test : System.Web.UI.Page 
{
    [WebMethod]
    public static string MyMethod(string name)
    {
        return "Hello " + name;
    }
}
A: 

Check out the following screencast. It explains how to call the PageMethods using JQuery:

http://www.highoncoding.com/Articles/430%5FCalling%5FPage%5FMethods%5FUsing%5FJQuery%5Fand%5FReturning%5FJSON%5FResult.aspx

azamsharp
Thank you, this worked. I would like to understand why using jQuery to make a JSON call worked but the "Microsoft way" did not. Thank you for your time!
Clay
I will try out with the Microsoft library and let you know. Thanks!
azamsharp
Sounds great, I hope you have better luck than I did! :)
Clay
Check out the answer below for calling PageMethods using Microsoft Ajax Library.
azamsharp
+2  A: 

You've to pass in a callback function that would be executed on Success / Exception. So in this case, it would be something like this

PageMethods.MyMethod("Joe Blow", onSuccess, onError);

function onError(desc) {
}

function onSuccess(result) {
}

I would check the documentation for the exact usage.

Vasu Balakrishnan
I've done this and it doesn't seem to help.
Clay
+3  A: 

Here is the answer on how to call PageMethods using MS Ajax. First make sure you have downloaded the latest Ajax library from the MS website.

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

    <input type="button" value="Greeting" onclick="greetings()" />

<script language="javascript" type="text/javascript">

    function greetings() {

       PageMethods.GreetingFromPage(function(response) {

            alert(response);

         });

    }


</script>

   [WebMethod]
        public static string GreetingFromPage()
        {
            return "greeting from page"; 
        }

That is pretty much it!

azamsharp
Thanks, the syntax here is slightly different from what I was using, I'll give this a shot.
Clay
+1 This does indeed work.
Steffen
A: 

So it's not possible to call function synchronously? That's pretty lame.

zhi wong