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.

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.

public static string ToUpper(string data) {
  return data.ToUpper();
Now on the javascript side create a few functions to make a call to the method on server side.

function CallMethod() {
  PageMethods.ToUpper("hello", CallSuccess, CallError);
function CallSuccess(res) {
function CallError() {
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 Call Failed callback function. Now call this CallMethod on onclientclick 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>
Post a Comment