Calling page methods from javascript using ASP.NET AJAX

We can call page methods (static methods declared in scope of page) using MS Ajax framework for ASP.NET. That is how can we do it : 1) Drop ScriptManager control on page 2) Set EnablePageMethods property of ScriptManager control to true 3) Add static public method in page-behind code (or its parent class) and mark it with [System.Web.Services.WebMethod] attribute: 4) add following javascript code to it
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
   <title>Untitled Page</title>

   <script type="text/javascript">
   function CallMethod()

   function GetTime()
   function TimeOutHandler(result)
        alert("Timeout :" + result);
   /// <summary>
   /// Callback function invoked on failure of the page method 
   /// </summary>
   function ErrorHandler(result)
       var msg=result.get_exceptionType() + "\r\n";
       msg += result.get_message() + "\r\n";
       msg += result.get_stackTrace();
  GetTimeCallback = function (result) {
   /// <summary>
   /// Is called when server sent result back
   /// </summary>
   /// <param name="result">
   /// Result of calling server method, 
   /// string - server time 
   /// </param>
   if(result) {
        $get("resultDiv").innerHTML = result;

   <form id="form1" runat="server">
       <asp:ScriptManager EnablePageMethods="true" ID="MainSM" runat="server" ScriptMode="Release"
       <div id="resultDiv">
       <input value="GetTime" type="button" onclick="GetTime();" />
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default2 : System.Web.UI.Page
   protected void Page_Load(object sender, EventArgs e)

   public static string GetTime()
       return DateTime.Now.ToString();


Post a Comment


  1. Nice example, but not very practical. The C# code-behind method has to be static for the javascript PageMethods to find it. If you need to do things to controls on the page, the C# functions have to be dynamic, not static, or you have to do all sorts of workarounds to get the controls (i.e. Page page = new Page(), page.FindControl("myTextBox"), etc.) and those don't instantiate the actual properties on those controls, like .Text, for example. If you had a way to call a dynamic method, that would be da bomb...

  2. You can pass the control's clientid in PageMethods

  3. i want to do validation on client side but calling server side method in javascript. if you have any solution please email me on


Please do not post any spam link in the comment box😊


Close Menu