Home » Development » PageMethods is not working (Solved)

PageMethods is not working (Solved)

PageMethods is a JavaScript class that you can use to call a server-side function. It’s basically an AJAX call which works asynchronously. In .NET world, you can use PageMethods to call a C# code-behind function. If you think that PageMethods is not working no matter what you do, keep reading.

For PageMethods to work, you need a JavaScript function on the client-side and a WebMethod function on the server-side.

Sample JavaScript code (Put it in asp:content section of Default.aspx):

<script type="text/jscript">

   function callCodeBehind() {
		PageMethods.GetMessage("test string", onSuccess, onFailure);
	}

   function onSuccess(result, usercontext, methodname) {
	   alert(result)
   }

   function onFailure(error, usercontext, methodname) { alert("failed: "+ error.get_message()); }

</script>

Sample C# code (code-behind file – Default.aspx.cs):

public partial class Welcome : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{

	}

	[WebMethod]
	protected static void GetMessage(string val)
	{
		return "doingit";
	}
}

A button to call the JavaScript function (in Default.aspx)

<button onclick="callCodeBehind()">Click me</button> 

ScriptManager (in Site.Master – note that EnablePageMethods is set to True):

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

Having issues with your AJAX call as part of Google reCAPTCHA implementation? Check this post out.

What to do if PageMethods is not working

If you have the code above, your project should be working. In exceptional cases, you may not receive the return value. In my case, the issue was the post-back that was happening after clicking the button.

The reason behind the post-back was that friendy URL setting. As soon as I disabled it, my PageMethods function started working.

In order to disable friendly URL feature, remove or comment out the line below in your RouteConfig file.

routes.EnableFriendlyUrls(settings)
Successfully returned value

Are you losing data after a post-back? Here is what to do.

References:

Ned Sahin

Blogger for 20 years. Former Microsoft Engineer. Author of six books. I love creating helpful content and sharing with the world. Reach me out for any questions or feedback.

Leave a Comment