jQuery AJAX with Page Method example in ASP.NET

This article gives you step by step example for implementing Page Method and calling it through jQuery.ajax() call.

This example will read data from Customer table of Northwind database. You can download the Northwind database here. Depending on the selected Country value of DropDown, Customer details will be rendered if jQuery.ajax() call returns success.

jQuery.Ajax()

jQuery library functions and methods have capabilities to load data from the server without a browser page refresh. jQuery.Ajax() performs an asynchronous HTTP request. This method can handle the response type of XML, JSON, script, or HTML. If you are making a request to other domain datatype jsonp should be used. You can perform asynchronously GET, POST, PUT or DELETE methods on the server using jQuery.Ajax().

jQueryAJAX solution

Create new solution of ASP.NET. Open visual studio click on File -> New -> Project -> ASP.NET Web Application name it as jQueryAjax and click Ok.

Design Customer page

Open Default.aspx or create new page with name Customer.aspx. In this step, we will add a DropDownList control to give users to select particular Country. You can also try with jQuery AutoComplete TextBox

We will also design a table object which will display Customer details on the selection of Country. The jQuery change event of DropDownList will be used to add rows to the table object.

Add below html in BodyContent ContentPlaceHolder of Default.aspx.


<asp:Content ID="BodyContent" runat="server" 
            ContentPlaceHolderID="MainContent">
    <div>
    Country:
    <asp:DropDownList ID="ddlCountry" runat="server">
        <asp:ListItem Text="Brazil" Value="Brazil"></asp:ListItem> 
        <asp:ListItem Text="France" Value="France"></asp:ListItem> 
        <asp:ListItem Text="Germany" Value="Germany"></asp:ListItem> 
        <asp:ListItem Text="Spain" Value="Spain"></asp:ListItem> 
        <asp:ListItem Text="USA" Value="USA"></asp:ListItem> 
        <asp:ListItem Text="UK" Value="UK"></asp:ListItem> 
        <asp:ListItem Text="Mexico" Value="Mexico"></asp:ListItem> 
    </asp:DropDownList> 
    </div>
    <br />
    <div>
    <table id="tblCustomers" class="tblCustomers" >            
        <thead>
            <tr>
                <th align="left" class="customerth">CustomerID</th>    
                <th align="left" class="customerth">CompanyName</th>    
                <th align="left" class="customerth">ContactName</th>    
                <th align="left" class="customerth">ContactTitle</th> 
                <th align="left" class="customerth">City</th>
                <th align="left" class="customerth">Phone</th>  
            </tr>
        </thead> 
        <tbody>
            
        </tbody> 
    </table>        
    </div>     
</asp:Content>

            

Apply css to Customer table

Open Site.css from Styles folder and add below styles to it. These styles are applied to table, table header and table row objects.

    
.tblCustomers
{
    font-family: verdana,arial,sans-serif; 
    font-size:11px;
    color:#333333;
    border-width: 1px;
    border-color: #666666; 
    border-collapse: collapse;    
}

.customerth
{
    border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #666666; 
    background-color: #dedede;   
}

.customertd
{
    border-width: 1px; 
    padding: 8px; 
    border-style: solid; 
    border-color: #666666; 
    background-color: #ffffff;  
}
                
            

Customer Entity

Add a new class as Customer.cs. This class will be used to hold customer details. jQuery.ajax() method will an get array of Customer object.

Add below properties to Customer.cs


public class Customer
{
    public string CustomerID { get; set; }
    public string CompanyName { get; set; }
    public string ContactName { get; set; }
    public string ContactTitle { get; set; }
    public string City { get; set; }        
    public string Phone { get; set; }
}
    
        

PageMethod for jQuery.Ajax()

Open codebehind file of Default.aspx page. Where we will add a PageMethod which takes Country as input parameter and return an array of Customer object.

It makes a database call to SQL Server and gets customer details depending on the provided country.

Add below code in Default.aspx.cs file. Notice that we have added [System.Web.Services.WebMethod] for GetCustomers method which allows access to methods by scripting method.

    
[System.Web.Services.WebMethod]
public static Customer[]  GetCustomers(string country)
{
    List<Customer> customers = new List<Customer>();
    string query = string.Format("SELECT [CustomerID], [CompanyName]," +
             " [ContactName], [ContactTitle]," +
             "[City], [Phone] FROM [Customers] " +
               "WHERE Country LIKE '%{0}%'", country);

    using (SqlConnection con =
            new SqlConnection("your connection string"))
    {
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            con.Open(); 
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                Customer customer = new Customer();
                customer.CustomerID = reader.GetString(0);
                customer.CompanyName = reader.GetString(1);
                customer.ContactName = reader.GetString(2);   
                customer.ContactTitle = reader.GetString(3);
                customer.City = reader.GetString(4);
                customer.Phone = reader.GetString(5);
                customers.Add(customer);   
            }
        }
    }
            
    return customers.ToArray();
}
                    
            

jQuery.Ajax()

In this step we will call PageMethod created in previous step. Create a new JavaScript file by open Solution Explorer -> right click on Scripts folder -> Select Add -> New Item -> Choose JScript -> Name it as Customer.js and click Ok

Add function for ddlCountry DropDownList's change event. Whenever user change the selection of country, PageMethod will be called through jQuery.Ajax(). If the call is a successful it will read Customer details and add each customer as table row to tblCustomers.


$(document).ready(function () {

$("#MainContent_ddlCountry").change(function () {
        
    $("#tblCustomers tbody tr").remove();

    $.ajax({
        type: "POST",
        url: "Default.aspx/GetCustomers",
        data: '{country: "' + $(this).val() + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            response($.map(data.d, function (item) {
                var rows = "<tr>"
                + "<td class='customertd'>" + item.CustomerID + "</td>"
                + "<td class='customertd'>" + item.CompanyName + "</td>"
                + "<td class='customertd'>" + item.ContactName + "</td>"
                + "<td class='customertd'>" + item.ContactTitle + "</td>"
                + "<td class='customertd'>" + item.City + "</td>"
                + "<td class='customertd'>" + item.Phone + "</td>"
                +"</tr>";
                $('#tblCustomers tbody').append(rows);
            }))
        },
        failure: function (response) {
            var r = jQuery.parseJSON(response.responseText);
            alert("Message: " + r.Message);
            alert("StackTrace: " + r.StackTrace);
            alert("ExceptionType: " + r.ExceptionType);
        }
    });
});
});

$("#tblCustomers tbody tr").remove(); removes existing rows from table object.

Url is mentioned as "Default.aspx/GetCustomers" which indicates where your PageMethod exists.

PageMethod takes country as input parameter which is mentioned with data property of $.ajax.

success: function (data) { } will execute when PageMethod executes successfully. It add row for each customer record.

failure: function (response) { } will execute if there is any error in execution of PageMethod and gives details of error.

Add a reference to script files

Open Site.Master file and add a reference to the script file in head tag of Master page.

Your head tag will look like this


<head id="Head1" runat="server">
    <title></title>
    <link href="~/Styles/Site.css"
         rel="stylesheet" type="text/css" />
    <script type="text/javascript"
         src="Scripts/jquery-1.4.1.min.js"></script>  
    <script   
        type="text/javascript" src="Scripts/Customer.js"></script>  
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>

read customer from server by jQuery Ajax

Source code on Git hub Source Code on Github

Speak your mind
Please login to post your comment!


  • geeksarray user
    05/05/2016 07:08 AM senzeye

    super explanation with source code . thank you.

  • geeksarray user
    05/18/2016 09:20 AM Laxmikant

    thanks senzeye, glad that it helped you

  • geeksarray user
    06/22/2016 01:55 PM Snowflake

    This is prime example on how to write tutorials, thank you champ! Keep it up :)

Blog Search





If you like my content please feel free to buy me coffee. Buy Me A Coffee