Home > Backend Development > C++ > How to Call ASP.NET Server-Side Methods from Client-Side JavaScript Using PageMethods?

How to Call ASP.NET Server-Side Methods from Client-Side JavaScript Using PageMethods?

Barbara Streisand
Release: 2024-12-25 13:53:24
Original
957 people have browsed it

How to Call ASP.NET Server-Side Methods from Client-Side JavaScript Using PageMethods?

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

Code-Behind Method:

[WebMethod]
public static string SetName(string name)
{
  // Server-side code
}
Copy after login

Calling Server Method from JavaScript:

PageMethods.SetName(name, onSuccessMethod, onFailMethod);
Copy after login

Other Requirements:

To enable PageMethods functionality, include the following in the ASPX page:

<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"></asp:ScriptManager>
Copy after login

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!

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