Wednesday, 25 February 2015

Call Server Side method from JavaScript using PageMethods in ASP.NET

In this article, I am going to write C# and JavaScript code sample to Call Server Side method from JavaScript Client Side code using PageMethods in ASP.NET.

Call Server Side method from JavaScript using PageMethods:

You can call server side method from JavaScript using Ajax ScriptManager's PageMethods. To use this you need to add ScriptManger tag in your page and enable property EnablePageMethods="True". Here, I have written an example to get web server time using PageMethods with Ajax call.

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side method from JavaScript in ASP.NET using PageMethods</title>
    <script type="text/javascript">
        function GetServerDate(format) {
            PageMethods.GetServerDate(format, OnSuccess, OnFailure);
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                document.getElementById("currentDate").innerHTML = dateTime;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scripman1" runat="server" EnablePageMethods="True">
    </asp:ScriptManager>
    <div>
        <input type="button" value="Show UTC Server Time" onclick="GetServerDate('utc')" />
        <input type="button" value="Show Local Server Time" onclick="GetServerDate('local')" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
   protected void Page_Load(object sender, EventArgs e)
   {
   }

   [System.Web.Services.WebMethod]
   public static string GetServerDate(string format)
   {
       if (format.Equals("utc"))
       {
           return DateTime.Now.ToUniversalTime().ToString();
       }
       else
       {
           return DateTime.Now.ToLocalTime().ToString();
       }
   }

Advertisements
Advertisements

No comments:

Post a Comment