Ajax-based data loading using jQuery.load() function in ASP.NET

In general, jQuery has made Ajax very easy by providing low-level interface, shorthand methods and helper functions, which all gives us great features of handling Ajax requests in our ASP.NET Webs.

The simplest way to load data from the server and place the returned HTML in browser is to use the jQuery.load() function. The very first time when I started playing with this function, I didn't believe it will work that much easy. What you can do with this method is simply call given url as parameter to the load function and display the content in the selector after which this function is chained. So, to clear up this, let me give you one very simple example:

$("#result").load("AjaxPages/Page.html");

As you can see from the above image, after clicking the ‘Load Content’ button which fires the above code, we are making Ajax Get and the Response is the entire page HTML.

So, rather than using (old) iframes, you can now use this method to load other html pages inside the page from where the script with load function is called.

This method is equivalent to the jQuery Ajax Get method

$.get(url, data, function () { })

only that the $.load() is method rather than global function and has an implicit callback function.

To provide callback to your load, you can simply add function as second parameter, see example:

$("#result").load("AjaxPages/Page.html", function () {
    alert("Page.html has been loaded successfully!")
});

Since load is part of the chain which is follower of the given jQuery Selector where the content should be loaded, it means that the $.load() function won't execute if there is no such selector found within the DOM.

Another interesting thing to mention, and maybe you've asked yourself is how we know if GET or POST method type is executed? It's simple, if we provide 'data' as second parameter to the load function, then POST is used, otherwise GET is assumed.

POST

$("#result").load("AjaxPages/Page.html", { "name": "hajan" }, function () {
    ////callback function implementation
});

 

GET

$("#result").load("AjaxPages/Page.html", function () {
    ////callback function implementation
});

 

Another important feature that $.load() has ($.get() does not) is loading page fragments. Using jQuery's selector capability, you can do this:

$("#result").load("AjaxPages/Page.html #resultTable");

In our Page.html, the content now is:

So, after the call, only the table with id resultTable will load in our page.

 

As you can see, we have loaded only the table with id resultTable (1) inside div with id result (2).

This is great feature since we won't need to filter the returned HTML content again in our callback function on the master page from where we have called $.load() function.

Besides the fact that you can simply call static HTML pages, you can also use this function to load dynamic ASPX pages or ASP.NET ASHX Handlers .

Lets say we have another page (ASPX) in our AjaxPages folder with name GetProducts.aspx. This page has repeater control (or anything you want to bind dynamic server-side content) that displays set of data in it. Now, I want to filter the data in the repeater based on the Query String parameter provided when calling that page. For example, if I call the page using GetProducts.aspx?category=computers, it will load only computers… so, this will filter the products automatically by given category.

The example ASPX code of GetProducts.aspx page is:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetProducts.aspx.cs" Inherits="WebApplication1.AjaxPages.GetProducts" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table id="tableProducts">
        <asp:Repeater ID="rptProducts" runat="server">
            <HeaderTemplate>
             <tr>
                <th>Product</th>
                <th>Price</th>
                <th>Category</th>
             </tr>
            </HeaderTemplate>
            <ItemTemplate>
               <tr>
                <td>
                    <%# Eval("ProductName")%>
                </td>
                <td>
                    <%# Eval("Price") %>
                </td>
                <td>
                    <%# Eval("Category") %>
                </td>
               </tr>
            </ItemTemplate>
        </asp:Repeater>
        </ul>
    </div>
    </form>
</body>
</html>

The C# code-behind sample code is:

public partial class GetProducts : System.Web.UI.Page
    {
        public List<Product> products;

        protected override void OnInit(EventArgs e)
        {
            LoadSampleProductsData(); //load sample data
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString.Count > 0)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["category"]))
                {
                    string category = Request.QueryString["category"]; //get query string into string variable

                    //filter products sample data by category using LINQ
                    //and add the collection as data source to the repeater
                    rptProducts.DataSource = products.Where(x => x.Category == category);
                    rptProducts.DataBind(); //bind repeater
                }
            }
            
        }

        //load sample data method
        public void LoadSampleProductsData()
        {
            products = new List<Product>();
            products.Add(new Product() { Category = "computers", Price = 200, ProductName = "Dell PC" });            
            products.Add(new Product() { Category = "shoes", Price = 90, ProductName = "Nike" });
            products.Add(new Product() { Category = "shoes", Price = 66, ProductName = "Adidas" });
            products.Add(new Product() { Category = "computers", Price = 210, ProductName = "HP PC" });
            products.Add(new Product() { Category = "shoes", Price = 85, ProductName = "Puma" });
        }
    }

    //sample Product class
    public class Product
    {
        public string ProductName { get; set; }
        public decimal Price { get; set; }
        public string Category { get; set; }
    }


Mainly, I just have sample data loading function, Product class and depending of the query string, I am filtering the products list using LINQ Where statement. If we run this page without query string, it will show no data.

If we call the page with category query string, it will filter automatically.

Example:

/AjaxPages/GetProducts.aspx?category=shoes

The result will be:

or if we use category=computers, like this /AjaxPages/GetProducts.aspx?category=computers, the result will be:

So, now using jQuery.load() function, we can call this page with provided query string parameter and load appropriate content…

The ASPX code in our Default.aspx page, which will call the AjaxPages/GetProducts.aspx page using jQuery.load() function is:

    <asp:RadioButtonList ID="rblProductCategory" runat="server">
        <asp:ListItem Text="Shoes" Value="shoes" Selected="True" />
        <asp:ListItem Text="Computers" Value="computers" />
    </asp:RadioButtonList>
    <asp:Button ID="btnLoadProducts" runat="server" Text="Load Products" />    
    <!-- Here we will load the products, based on the radio button selection-->
    <div id="products"></div>
    </form>

The jQuery code:
$("#<%= btnLoadProducts.ClientID %>").click(function (event) {
    event.preventDefault(); //preventing button's default behavior
    var selectedRadioButton = $("#<%= rblProductCategory.ClientID %> input:checked").val();

    //call GetProducts.aspx with the category query string for the selected category in radio button list
    //filter and get only the #tableProducts content inside #products div 
    $("#products").load("AjaxPages/GetProducts.aspx?category=" + selectedRadioButton + " #tableProducts");

});

The end result:

You can download the code sample from here.

You can read more about jQuery.load() function here.

I hope this was useful blog post for you.

Please do let me know your feedback.

Best Regards,
Hajan

8 Comments

  • Thanx for this post. Very easy to understand.

  • Thanks for a great tutorial, a step by step with explanations is always fantastic, easy to translate this one to real life application too.

  • Joanelle & David, thanks for the nice comments. I am glad it was helpful and easy to understand.

  • Very nice man, thanks. I have a winform app using the WebBrowser control and was wondering how I was going to do the same on a web app. I think I will get it done with this (jQuery and load method) since I can control all of the DOM elements with jQuery the same way I would control it with the WebBrowser. 5/5

  • Very useful, thanks for sharing.

  • Hamlet & Yousef, I am glad the blog was very useful to you ;)!

  • I have a gridview, one column template is &lt;asp:LinkButton&gt;. On RowDataBound event of the gridview, I want to add event OnClientClick to these LinkButton.

    How to do? Please help..

    Here my code, but it is not working

    protected void grdCustomers_RowDataBound(object sender, GridViewRowEventArgs e)

    &nbsp; &nbsp;{

    &nbsp; &nbsp; &nbsp; &nbsp;if (e.Row.RowType == DataControlRowType.DataRow)

    &nbsp; &nbsp; &nbsp; &nbsp;{

    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;LinkButton lnk = e.Row.FindControl(&quot;lnkDetails&quot;) as LinkButton;

    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;DataRowView row = e.Row.DataItem as DataRowView;

    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (lnk != null)

    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{

    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;StringBuilder strBuilder = new StringBuilder();

    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;strBuilder.Append(&quot;function (event) {alert('ksalfjaoweijo');&quot;);

    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;strBuilder.Append(&quot;event.preventDefault(); &quot;);

    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;strBuilder.Append(&quot;$('#divCusDetails').load('CustomerDetails.aspx?clntnum=&quot; + row[&quot;CLNTNUM&quot;].ToString() + &quot;')&quot;);

    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;strBuilder.Append(&quot;});&quot;);

    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;lnk.OnClientClick = strBuilder.ToString();

    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}

    &nbsp; &nbsp; &nbsp; &nbsp;}

    &nbsp; &nbsp;}

  • When i use load() function to load a page with Microsoft UpdatePanel control in it. The page is loaded OK.

    In the page have a text box and button.

    The first time i press button, it work well, but i press the &nbsp;button again then error happen.

    The error is:

    Sys.WebForms.PageRequestManagerServerErrorException: The state information is invalid for this page and might be corrupted.

Comments have been disabled for this content.