Call PageMethod From jQuery $. Ajax

Introduction

ASP.NET has very good feature, PageMethod (System.Web.Services.WebMethod). We can call any method which is written in page code behind. We can call it by using jQuery. There are a few constraints while making PageMethod.

You can add static page methods to an ASP.NET page and mark them as Web methods. You can then call these methods from script as if they were part of a Web service, but without creating a separate .asmx file. To create Web methods on a page, import the System.Web.Services namespace and add a WebMethodAttribute attribute to each static method that you want to expose. The methods must be marked public more.

Code

First we have to include the jQuery library.

<script type="text/javascript" src="Scripts/jquery-ui-1.8.11.min.js"></script>
<
script type="text/javascript" src="Scripts/jquery-1.6.2.js"></script>
<
script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="Scripts/jquery-ui-1.8.11.js"></script>

Create PageMethod in the aspx only:

<script runat="server">
        [System.Web.Services.WebMethod]
       
public static string GetData()
        {
           
if (CheckStatus() == 0)
               
return "Hello World";
           
else
                return "Hello India";
        }
</script>

Create another static method inside the code behind page:

public static int CheckStatus() {
 
return 1;
}

Now we will make a call from jQuery in Ajax:

<script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type:
"POST",
                url:
"Default.aspx/GetData",
                contentType:
"application/json; charset=utf-8",
                dataType:
"json",
                success:
function (data) {
                    alert(data.d);
                    $(
"#ctl10_lnkRegister").hide(10);

                }
            });
        });
    </script>

Here is the output screen.

Jquery.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all