PAGEMETHODS is not working from JS function

user3212507 picture user3212507 · Jan 19, 2014 · Viewed 12.1k times · Source

I am trying to call code behind method from JS function using pagemethods but its not calling and its not throwing any error either...

function example(){

pagemethods.method();
}

**aspx.cs
[webmethod]
public static void method(){

//some logic
}

so to find the issue i did some negative testing for that

  1. I commented WEBMETHOD then it showed an error by saying"object does not support this property or method".can i assume this case shows pagemethods is working!!!

  2. Then I replaced calling method name in JS function to pagemethods.newmethod() but i didn't change method name to newmethod..i was expecting an some error but it didn't give me an error..

NOTE:i have "method=post" in form declaration..does it effect pagemethods anything..

so confused why this issue is happening!!!

can we call codebehind method in any other way instead of pagemethods..please advice!!!

Answer

Grundy picture Grundy · Jan 20, 2014

in msnd you can see a sample of this, so you need...

in markup:

<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true">
    <Scripts >
        <asp:ScriptReference Path="pm.js" />
    </Scripts>
</asp:ScriptManager>

in code behind: your static method, with attribute [WebMethod]

in pm.js: something like this

function example(){
    PageMethods.method();
}

UPDATE
Another variant is use an ajax request to your method, for example with jquery in goes like this:

function CallMethod(){
    $.ajax({
        type: "POST",
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        url: "YourPage.aspx/yourmathod",
        data:JSON.stringify({}), // parameters for method
        success: function (dt) { alert(dt);}, //all Ok
        error: function () { alert('error'); } // some error
    });
}