Invoking Server-Side Methods from Client-Side JavaScript
In this scenario, you aim to invoke a server-side method in the code-behind page from a JavaScript function triggered by a button click. Here's a comprehensive solution without using ASP.NET controls:
To achieve this, you need to employ a web method in your code-behind. A web method is a method in the code-behind page that can be invoked remotely from a client-side script.
Modified Code-Behind (C#):
[WebMethod] public static string SetName(string name) { // Perform some server-side functionality here return "Success"; }
JavaScript Function:
function btnAccept_onclick() { var name = document.getElementById('txtName').value; // Invoke the SetName web method with the 'name' parameter PageMethods.SetName(name, function (result) { // Success handler: Perform post-invocation actions }, function (error) { // Error handler: Handle invocation failures }); }
Additional Requirements:
To execute the JavaScript code successfully, you must include the following scripts in your ASPX page:
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"></asp:ScriptManager>
Usage:
When the user clicks the HTML button, the JavaScript function btnAccept_onclick() is triggered, which passes the 'name' parameter to the web method SetName(). The web method performs the desired functionality on the server-side and responds with a result or error message.
Note: This approach requires a Web Forms page, unlike the scenario where ASP.NET controls are not permitted. The script manager ensures the correct execution of the web service calls from the client-side.
The above is the detailed content of How to Invoke Server-Side Methods from Client-Side JavaScript in ASP.NET Web Forms?. For more information, please follow other related articles on the PHP Chinese website!