Calling page methods from JavaScript using ASP.NET AJAX

We can call page methods (static methods declared in the scope of asp.net 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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>

   <script type="text/javascript">
   function CallMethod()
   {
       GetTime();
   }

   function GetTime()
 
   {
 
       PageMethods.GetTime(GetTimeCallback,ErrorHandler,TimeOutHandler);
                  
 
   }
   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();
       alert(msg);
   }
  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;
   }
}
   </script>

</head>
<body>
   <form id="form1" runat="server">
       <asp:ScriptManager EnablePageMethods="true" ID="MainSM" runat="server" ScriptMode="Release"
           LoadScriptsBeforeUI="true">
       </asp:ScriptManager>
       <div id="resultDiv">
       </div>
       <input value="GetTime" type="button" onclick="GetTime();" />
   </form>
</body>
</html>

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)
   {

   }
   [System.Web.Services.WebMethod]
   public static string GetTime()
   {
       return DateTime.Now.ToString();
   }

}

Post a Comment

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

Previous Post Next Post

Blog ads

CodeGuru