Wednesday, 1 January 2014

jQuery AJAX with Page Method example in ASP.NET

This article gives you step by step example for implementing WebMethod and calling it through jQuery.ajax() method.
This example will read data from Customer table of Northwind database. You can download Northwind database . Depending on selected Country value of DropDown, Customer details will be render if jQuery.ajax() call returns success.


jQuery library functions and methods has capabilities to load data from server without a browser page refresh. jQuery.Ajax() performs an asynchronous http request. This method can handle 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 server using jQuery.Ajax().

Implementing PageMethod with jQuery.Ajax() in ASP.NET

  1. 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.
  2. 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 user to select particular Country. You can also try with jQuery
    We will also design a table object which will display Customer details on selection of Country. The jQuery change event of DropDownList will be used to add rows to table object.
    Add below html in BodyContent ContentPlaceHolder of Default.aspx.
    <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
        <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> 
        <br />
        <table id="tblCustomers" class="tblCustomers" >            
                    <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>  
  3. 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.
            font-family: verdana,arial,sans-serif; 
            border-width: 1px;
            border-color: #666666; 
            border-collapse: collapse;    
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #666666; 
            background-color: #dedede;   
            border-width: 1px; 
            padding: 8px; 
            border-style: solid; 
            border-color: #666666; 
            background-color: #ffffff;  
  4. Customer Entity

    Add new class as Customer.cs. This class will be used to hold customer details. jQuery.ajax() method will 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; }
  5. PageMethod for jQuery.Ajax()

    Open codebehind file of Default.aspx page. In this file we will add a PageMethod which takes country as input parameter and return array of Customer object.
    It makes a database call to SQL Server and get customer details depending on 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.
    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))
                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);
        return customers.ToArray();
  6. 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 will change selection of country, PageMethod will be called through jQuery.Ajax(). If call is successfull 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();
                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>"
                        $('#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.
  7. Add reference to script files

    Open Site.Master file and add reference to script file in head tag of Master page.
    Your head tag will look like this
    <head id="Head1" runat="server">
        <link href="~/Styles/Site.css"
             rel="stylesheet" type="text/css" />
        <script language="javascript" type="text/javascript"
        <script language="javascript"  
            type="text/javascript" src="Scripts/Customer.js"></script>  
        <asp:ContentPlaceHolder ID="HeadContent" runat="server">

read customer from server by jQuery Ajax
Post a Comment