Home > Backend Development > C++ > How to Invoke Server-Side Methods from Client-Side JavaScript in ASP.NET Web Forms?

How to Invoke Server-Side Methods from Client-Side JavaScript in ASP.NET Web Forms?

Linda Hamilton
Release: 2024-12-30 19:37:11
Original
430 people have browsed it

How to Invoke Server-Side Methods from Client-Side JavaScript in ASP.NET Web Forms?

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";
}
Copy after login

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
        });
}
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template