Calling Code Behind Server Method from Client Side JavaScript
In ASP.NET pages, it's often necessary to invoke server-side methods from JavaScript functions for various client-side interactions. To accomplish this, we can employ the PageMethods feature.
Consider the following scenario: we have a JavaScript function attached to an HTML button click event and a server method in the code-behind page. Our goal is to call the server method with parameters when the HTML button is clicked by the user.
JavaScript Code:
function btnAccept_onclick() { var name = document.getElementById('txtName').value; // Call server method SetName() with 'name' parameter }
Code-Behind Method:
[WebMethod] public static string SetName(string name) { // Server-side code }
Calling Server Method from JavaScript:
PageMethods.SetName(name, onSuccessMethod, onFailMethod);
Other Requirements:
To enable PageMethods functionality, include the following in the ASPX page:
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"></asp:ScriptManager>
By utilizing PageMethods, we can seamlessly connect client-side JavaScript functions with server-side code, facilitating comprehensive user interactions.
The above is the detailed content of How to Call ASP.NET Server-Side Methods from Client-Side JavaScript Using PageMethods?. For more information, please follow other related articles on the PHP Chinese website!