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.

<html xmlns="">
<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) {
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scripman1" runat="server" EnablePageMethods="True">
        <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>

   protected void Page_Load(object sender, EventArgs e)

   public static string GetServerDate(string format)
       if (format.Equals("utc"))
           return DateTime.Now.ToUniversalTime().ToString();
           return DateTime.Now.ToLocalTime().ToString();


No comments:

Post a Comment