javascriptc#asp.netwebmethodpagemethods

PageMethods is not defined Exception: Does not call the WebMethod in ASP.NET


My WebMethod does not get called by the PageMethod call in my Javascript function. Here's the code:

EDIT The Console says:

Uncaught ReferenceError: PageMethods is not defined

JS:

    function profilefollowbuttonchange(cn) {
        if (cn.className == "profile-page-owner-follow-button") {
                cn.className = "profile-page-owner-follow-button-active";
                alert("camefollow");
                PageMethods.ToggleFollow("follow", onSuccess, onFailure); //Does not trigger
                alert("camefollow"); //Doesn't get printed
            }

            else {
                cn.className = "profile-page-owner-follow-button";
                alert("cameunfollow");
                PageMethods.ToggleFollow("unfollow", onSuccess, onFailure); //Does not trigger
                alert("cameunfollow"); //Doesn't get printed
            }   
    }

function onSuccess() {
}

function onFailure() {
}

C#:

[WebMethod]
public static void ToggleFollow(string command)
{
       //Does not reach this point. 
}

And yes I have added the EnablePageMethods="true" tag in the ScriptManager tag.

However, I have used two WebMethods in the same page for two different purposes (Two different names). Could that be the issue? I hardly think so, but what do yall think?


Solution

  • It looks like the problem is with your execution sequence of the script and the ScriptManager. This means that to make sure the PageMethods is recognized by the Javascript code, you need to load the ScriptManager first and then fire that Javascript function. So in my logic, a simple change is required here. You need to use $(document).ready() here in your script to make sure that ScriptManager first into the DOM and then your script is fired. Something like this should help here.

    $(document).ready(function () {
    function profilefollowbuttonchange(cn) {
            if (cn.className == "profile-page-owner-follow-button") {
                    cn.className = "profile-page-owner-follow-button-active";
                    alert("camefollow");
                    PageMethods.ToggleFollow("follow", onSuccess, onFailure); //Does not trigger
                    alert("camefollow"); //Doesn't get printed
                }
    
                else {
                    cn.className = "profile-page-owner-follow-button";
                    alert("cameunfollow");
                    PageMethods.ToggleFollow("unfollow", onSuccess, onFailure); //Does not trigger
                    alert("cameunfollow"); //Doesn't get printed
                }   
        }
    
    function onSuccess() {
    }
    
    function onFailure() {
    }
    });
    

    Just wrap your script code with $(document).ready() and then try it.

    Hope this helps.