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:

How to simulate keyboard key press in JavaScript using jQuery?

You may need your user to press a certain key as part of your application flow. Use the line below if you want to automatize this action. In this example, “77” is the character code for the letter “m”. Change it to the key you want to simulate pressing (JavaScript Key Codes).

jQuery.event.trigger({ type: 'keydown', which: 77 });

If you want to simulate the situation where user presses 2 keys at the same time in an input field, use the code block below. It assumes that user presses Alt + M

var e = jQuery.Event("keydown");
e.which = 77; // m code value
e.altKey = true; // Alt key pressed
$("#inputBox").trigger(e);

Note: Depending on the browser, you may need to use “keypress” event instead of “keydown” event.

References: