Calling Server-Side Methods from JavaScript Client-Side Code
You aim to invoke a code-behind method from a JavaScript function triggered by a button click event. This specific scenario prohibits the use of ASP.NET controls in the ASPX page.
To achieve this, you can leverage the ASP.NET WebMethods feature. Here's a step-by-step guide:
1. Define the Server-Side Method (Web Method):
In your code-behind file, define a public method decorated with the [WebMethod] attribute:
[WebMethod] public static void SetName(string name) { // Implementation of your desired functionality here }
2. Modify the JavaScript Function:
In your JavaScript function, utilize the PageMethods object to call the Web Method:
function btnAccept_onclick() { var name = document.getElementById('txtName').value; PageMethods.SetName(name); // Pass 'name' as a parameter }
3. Register the Script Manager (in the ASPX page):
Include a Script Manager control to enable WebMethods functionality:
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"></asp:ScriptManager>
By following these steps, you can bridge the communication gap between your client-side JavaScript code and server-side code-behind methods.
The above is the detailed content of How to Call Server-Side Methods from Client-Side JavaScript without ASP.NET Controls?. For more information, please follow other related articles on the PHP Chinese website!