How to call page methods with javascript.


PageMethods” is the keyword which is used for calling your code behind methods inside javascript function. To implement PageMethods functionality we need to consider three points.

  • EnablePageMethods property to true in ScriptManager on your page.
  • Calling method should be Static.
  • use [System.Web.Services.WebMethod]  on your Static method.

Example :

<script type="text/javascript">
  function Test() 
  {
     PageMethods.TestYourMethod(onSuccess, onError);          
  } 
  function onSuccess(result) 
  {
    alert("Result " + result); 
  }
  function onError(error) 
  { 
     alert("error " + error); 
  }
</script>
 [System.Web.Services.WebMethod]
    public static string TestYourMethod()
    {
        try
        {
            return "Hello";           
        }
        catch (Exception ex)
        {
           return ex.message.tostring();
        }
    }
<asp:ScriptManager EnablePageMethods="true" ID="ScriptManager1" runat="server"></asp:ScriptManager>