Calling page methods from JavaScript using ASP.NET AJAX

We can call page methods (static methods declared in the scope of page) using the MS Ajax framework for ASP.NET. That is how can we do it

  • Drop ScriptManager control on page
  • Set EnablePageMethods property of ScriptManager control to true
  • Add static public method in page-behind code (or its parent class) and mark it with [System.Web.Services.WebMethod] attribute
  • 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();

Next Post Previous Post
No Comment
Add Comment
comment url