An Asp.Net Way to Call Server Side Methods Using JavaScript


One of the most popular and most widely used methods of making server side calls from client side is by using jQuery AJAX. Asp.NET provides an easier approach to make server side calls from client side using Page Methods.This method is also popular due to its simpler syntax and much less code as compared to jQuery AJAX. In this tutorial, we’ll see An Asp.Net Way to Call Server Side Methods Using JavaScript.

Here is an example which demonstrates the use of Page Methods.

First of all in the server side create a method which needs to be called. Let us call the method ToUpper which returns the Upper Case string as response.

[System.Web.Services.WebMethod]
public static string ToUpper(string data) {
  return data.ToUpper();
}

On the client side create function to make a call to the method on server side. It should look like:

function CallMethod() {
  PageMethods.ToUpper("hello", OnSuccessCallback, OnFailureCallback);
}
 
function OnSuccessCallback(res) {
  alert(res);
}
 
function OnFailureCallback() {
  alert('Error');
} 

Now its the CallMethod function which calls the method on server side.The first parameter is the input parameter, the second parameter is the success callback function and third one is the failure callback function.

Call the CallMethod on on client click event of your button.

<asp:button id="btn" onclientclick="CallMethod();return false;" runat="server"> </asp:button>

Before running the code don’t forget to include the Script Manager in your aspx page and also enable the page methods as shown below.

<asp:scriptmanager enablepagemethods="true" id="scpt" runat="server"> </asp:scriptmanager>

In this quick tip tutorial, we saw an An Asp.Net Way to Call Server Side Methods Using JavaScript. If you have used any other ways to call server side method using JavaScript, feel free to comment in the section below.