Thursday, April 18, 2013

Calling an ASP .NET page method

A sample page method
The following is the code sample of a sample page method that takes no parameters
[WebMethod()]
public static string Hello2()
{
    return "hello ";
}
Please note that page methods must be declared as static, meaning a page method is completely self-contained, and no page controls are accessible through the page

method. For example, if you have a textbox on the web form, there is no way the page method can get or set its value. Consequently any changes with regards to the

controls have no affect on the page method. It is stateless and it does not carry any of the view-state data typically carries around by an asp .NET page.

Calling a page method from jQuery:
We use the same jQuery command $.ajax to call a page method, as shown in the following example.
<script type="text/javascript">
      $(document).ready(function() {
          $.ajax({
              type: "POST",
              url: "pagemethod.aspx/Hello2",
              contentType: "application/json; charset=utf-8",
              data: "{}",
              dataType: "json",
              success: AjaxSucceeded,
              error: AjaxFailed
          });
    });
      function AjaxSucceeded(result) {
          alert(result.d);
      }
      function AjaxFailed(result) {
          alert(result.status + ' ' + result.statusText);
      } 
  </script>

No comments:

Post a Comment