Bind GridView Using jQuery Load In ASP.NET With No Page Reload

GridView is a powerful control in ASP.NET. It can can be used to show the data in grid format (rows and columns). Typically, when we bind a GridView with the data, then there is  page reloading. This page reload can sometimes be frustrating to the users, so as a developer, you may think of removing this page reloading when binding the GridView.


Avoid Update Panel & Update Progress

The first thought which comes to your mind is to use ASP.NET AJAX controls. These are the Update Panel and Update Progress. Although they are simple to use, I recommend you not to use them in your Websites.

I say this because they

  1. They make your page heavy by including too many unnecessary scripts.
  2. Slows down your page.
  3. Breakpoints may stop working in Visual Studio during the code debugging.
  4. May give you new headaches due to the problems that can arise due to them. Some problems are listed below.

    1. Some button clicks may not in your page.
    2. AJAX is not working properly.
    3. Other features of the page stops working at all.

I myself have noticed such problems in the page and these gave me too many headaches. Thus, I decided not to use them any further. Hence, you should not use Update Panel & Update Progress in your Website.

Use jQuery instead of Update Panel & Update Progress

You can just avoid these AJAX controls and instead use jQuery to do all sorts of AJAX works. The jQuery is just a JavaScript library, which is very easy to lean, and makes code execution fast. Moreover, it does not make your page heavy and slow.

Therefore, let us use jQuery to make AJAX calls and let me prove my point.

Bind GridView with no page reload

Let us see how to bind a GridView in such a way that there is no page reload. We will just use an AJAX method from jQuery to do this work. This method name is jQuery Load, which can be used to load the text, XML, JSON, HTML etc. from the external files.

Here, we will use 2 pages – first is a “ASP.NET page”, which contains the GridView while the second is HTML page from where the AJAX calls will be made.

The code of ASP.NET page

Name the page “result.aspx” or any name you want. In this page, we have a GridView control and we bind this control from the database values.

For the purpose of this tutorial, I have taken “Northwind” database and I am fetching the values from “Products” table.

In my SQL query, I am applying the “Where” clause to filter the products by ProductName and this ProductName, which I am getting through “Request.Form["productName"]” in my page.

The C# code of the page is given below,
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (!IsPostBack)  
  4.         BindGridView();  
  5. }  
  6.   
  7. void BindGridView()  
  8. {  
  9.     string productName = Request.Form["productName"];  
  10.     string query = productName == "All" ? "SELECT PRODUCTNAME,QUANTITYPERUNIT,UNITPRICE,UNITSINSTOCK FROM PRODUCTS" : "SELECT PRODUCTNAME,QUANTITYPERUNIT,UNITPRICE,UNITSINSTOCK FROM PRODUCTS WHERE PRODUCTNAME='"+ productName + "'";  
  11.   
  12.     SqlConnection conn = new SqlConnection();  
  13.     SqlCommand cmd = new SqlCommand();  
  14.     DataTable dataTable = new DataTable();  
  15.     conn.ConnectionString = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;  
  16.     cmd.Connection = conn;  
  17.   
  18.     cmd.CommandType = CommandType.Text;  
  19.     cmd.CommandText = query;  
  20.     cmd.Connection = conn;  
  21.   
  22.     SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();  
  23.     sqlDataAdapter.SelectCommand = cmd;  
  24.     try  
  25.     {  
  26.         sqlDataAdapter.Fill(dataTable);  
  27.         gridView.DataSource = dataTable;  
  28.         gridView.DataBind();  
  29.     }  
  30.     catch (Exception ex)  
  31.     {  
  32.         Response.Write(ex.Message);  
  33.     }  
  34.     finally  
  35.     {  
  36.     }  
  37. }  
The .ASPX page code is given below.
  1. <asp:GridView ID="gridView" runat="server">  
  2.     <Columns>  
  3.         <asp:TemplateField HeaderText="Serial No">  
  4.             <ItemTemplate>  
  5.                 <%#Container.DataItemIndex+1 %>  
  6.             </ItemTemplate>  
  7.         </asp:TemplateField>  
  8.     </Columns>  
  9. </asp:GridView>  

The code of the HTML page

In HTML page, we will bind GridView of ASP.NET page and show that GridView is here in HTML page. In HTML page, we have the controls given below..

 

  1. Select
    It contains the product names. They will used to filter the database values and we use them in the where clause of the SQL query (see the query given in ASP.NET code).

  2. Button
    The button click will call the jQuery load method. The load method will cause the GridView of the ASP.NET page to bind with the database values.

  3. Div
    Div is used to show the GridView of ASP.NET page.

  4. Image
    It is a loading .GIF image that will be shown during AJAX calls.

 

HTML code of the page is given below.

  1. <div class="container">     
  2.     <div id="content">  
  3.         <h3>Bind GridView using jQuery Load</h3>  
  4.         <select id="productSelect">  
  5.             <option value="All">All</option>  
  6.             <option value="Chai">Chai</option>  
  7.             <option value="Chang">Chang</option>  
  8.             <option value="Konbu">Konbu</option>  
  9.             <option value="Tunnbröd">Tunnbröd</option>  
  10.         </select>  
  11.         <button id="bindButton">Click Here</button>  
  12.         <div class="imageDiv">  
  13.             <img src="loading.gif" />  
  14.         </div>  
  15.         <div id="gridViewDiv"></div>  
  16.     </div>  
  17. </div>  

To style HTML controls, add CSS to the Page Head section.

  1. <style>  
  2.     .container {  
  3.         width960px;  
  4.         marginauto;  
  5.         color#FFF;  
  6.         font-size25px;  
  7.     }  
  8.   
  9.         .container h3 {  
  10.             font-size25px;  
  11.             text-decorationunderline;  
  12.             text-alignleft;  
  13.         }  
  14.   
  15.         .container #content {  
  16.             borderdashed 2px #CCC;  
  17.             padding10px;  
  18.         }  
  19.   
  20.             .container #conten#gridViewDiv {  
  21.                 padding-top20px;  
  22.             }  
  23.   
  24.             .container #conten#gridViewDiv {  
  25.                 margin-top20px;  
  26.             }  
  27.   
  28.                 .container #conten#gridViewDiv tr:nth-child(1) {  
  29.                     background#0184e3;  
  30.                 }  
  31.   
  32.             .container #content .imageDiv {  
  33.                 text-aligncenter;  
  34.             }  
  35.   
  36.                 .container #content .imageDiv img {  
  37.                     displaynone;  
  38.                 }  
  39. </style>  

To start up with jQuery, first include its reference in your HTML page, as shown below.

  1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>  

Note

Put this reference just before the ending body tag of your page.

Now, add the jQuery code given below after jQuery reference.

  1. <script>  
  2.     $(document).ready(function () {  
  3.         $("#bindButton").click(function (e) {  
  4.             $("#gridViewDiv").load("result.aspx #gridView", { "productName""" + $("#productSelect").val() + "" }, function (response, status, xhr) {  
  5.                 if (status == "error")  
  6.                     $("#gridViewDiv").html("Error: " + xhr.status + ": " + xhr.statusText);  
  7.             });  
  8.         });  
  9.   
  10.         $(document).ajaxStart(function () {  
  11.             $("img").show();  
  12.         });  
  13.   
  14.         $(document).ajaxStop(function () {  
  15.             $("img").hide();  
  16.         });  
  17.     });  
  18. </script>  

Explanation

We place jQuery code inside the “$(document).ready(function () { //code });” block. Inside this, we have created the button click event for the button with Id “bindButton”.

In this button click event, we are calling the jQuery Load method to do the AJAX call. It calls ASP.NET page and loads the GridView by providing GridView’s Id “#gridView”.

It is also passing the value of the select to ASP.NET page and shows the GridView inside the div with an Id “gridViewDiv”.

In general, the syntax of jQuery load method is given below.
  1. $("Div Id where GridView will be shown").load("asp.net page #gridView id", { "value to send""value of the select" }, function (response, status, xhr) {  
  2.        //code that executes when the AJAX call finishes    
  3.     });  
  4. });  

The ajaxStart() event is called, when the AJAX request starts. In this event, we had shown the loading .GIF image. Similarly, the ajaxStop() event is called, when the AJAX request finishes. In this event, we hide the loading image.

How it all works

We have written the full jQuery Load code. Now, it’s time to check how it works. The user can select a value from the select control and click the button. On clicking the button, jQuery load calls ASP.NET page, binds it with the database values and shows the GridView inside a div.

Everything is done with no page reload, as the work is done with AJAX, using jQuery.

Conclusion

I hope, you enjoyed this tutorial and can now understand that it is very easy to make AJAX features with jQuery. Please share this on Facebook, Twitter and your other social accounts, so that your friends can also know about this tutorial.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now