PageMethods returning undefined result?

12,923

Solution 1

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

http://www.highoncoding.com/Articles/430_Calling_Page_Methods_Using_JQuery_and_Returning_JSON_Result.aspx

Solution 2

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!

Solution 3

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.

Share:
12,923
Clay
Author by

Clay

Updated on June 05, 2022

Comments

  • Clay
    Clay about 2 years

    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;
        }
    }
    
  • Clay
    Clay almost 15 years
    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!
  • azamsharp
    azamsharp almost 15 years
    I will try out with the Microsoft library and let you know. Thanks!
  • Clay
    Clay almost 15 years
    Sounds great, I hope you have better luck than I did! :)
  • azamsharp
    azamsharp almost 15 years
    Check out the answer below for calling PageMethods using Microsoft Ajax Library.
  • bebosh
    bebosh over 6 years
    what if the function has parameters?