Lazy Loading Grid using Repeater for ASP.NET


Hi Guys,

This time I made a Grid which fetches data as you scroll down and appends it to the end of the Grid. Which eventually makes your grid works faster and look responsive. I saw this in yahoo mail and wanted to do something like it. So here it goes,


Before you Start,

1) Any version of Visual Studio 

Step One : The Solution

Make a Web Site Application as Following,
















Step Two : Open the Default.aspx page and paste the following code

<html>
    <head>
        <link href="css/layout.css" rel="stylesheet" type="text/css" />
        <!--[if lt IE 9]>
   <link rel="stylesheet" href="css/ie.css" type="text/css" media="screen" />
   <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
   <![endif]-->

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

        <script src="js/jquery-1.5.2.min.js" type="text/javascript"></script>

        <script src="js/hideshow.js" type="text/javascript"></script>

        <script type="text/javascript" src="js/jquery.equalHeight.js"></script>

        <script type="text/javascript">

    var pageIndex = 1;
    //Event to get the Scroller End Point is reached 
    function GetScrollerEndPoint()
    {

     try
     {
       var scrollHeight = document.getElementById("module").scrollHeight;
       var curPage = parseInt($('#'+'<%= CurrentPage.ClientID %>').val());
       var pages = parseInt($('#'+'<%= Pages.ClientID %>').val());
       var divHeight = $("#module").height();
       var scrollerEndPoint = scrollHeight - divHeight;

       var divScrollerTop =  $("#module").scrollTop();
        
       var dvText = document.getElementById("dvText");

       dvText.innerHTML = "<b> divScrollerTop : </b> " + divScrollerTop + "<br> <b>scrollerEndPoint : </b>" + scrollerEndPoint;
       
           if (divScrollerTop >= scrollerEndPoint)
           {      
              //Scroller End Point is reached 
              ajaxCall();   
           }
       
        }
        catch(e)
        {
          alert("Main Error : " + e);
        }
         
    }

    //Function to make the Ajax Call and bring data
    function ajaxCall()
    {
     $.ajax({
                type: "POST",
                url: "./DataService.asmx/GetSongs?pageIndex=" + (pageIndex++),
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert("failure : "+response.d);
                },
                error: function (response) {
                    alert("error : "+ response.d);
                }
            }); 
        

    }

    //Method to append Data to the End of the Grid
    function OnSuccess(response) {


            var xmlDoc = $.parseXML(response.d);            
            var xml = $(xmlDoc);          
            var customers = xml.find("cd");                    
            var rowCount = Math.ceil(customers.length);            
           
            var row;      
                
                for (var j = 10; j < rowCount; j++) {
                    var customer = $(customers[j]);
                   
                    if (customer.length == 0) {
                       //Do Nothing
                    } else {
                    row = "<table class=\"tablesorter\" cellspacing=\"0\"> "+
   "<tbody>" +
   "<tr>" +
       "<td width=\"5%\"> <input type=\"checkbox\" class=\"chkBoxClass\"></td> ";
                        row += "<td width=\"18%\"><span Class=\"title\" >"+customer.find("title").text()+" </span></td>";                
       row += "<td width=\"18%\"><span Class=\"artist\" >"+customer.find("artist").text()+"</span></td>";    
       row += "<td width=\"18%\"><span Class=\"country\" >"+customer.find("country").text()+"</span></td>";
       row += "<td width=\"18%\"><span Class=\"company\" >"+customer.find("company").text()+"</span></td>";
       row += "<td width=\"18%\"> <span Class=\"price\" >"+customer.find("price").text()+"</span></td>";
       row += "<td width=\"13%\"><input type=\"image\" src=\"images/icn_edit.png\" onclick=\"return showModal()\" title=\"Edit\"><input type=\"image\" src=\"images/icn_trash.png\" title=\"Trash\"></td> ";
   row += "</tr>";
   row += "</tbody>";
   row += "</table>";
                        
                         
                         
                    }
                    
                    $("[id*=module]").append(row);
                    
                }
               
           
            $("[id*=module]").show();
        }


        </script>

    </head>
    <body>
        <form id="form2" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
        </asp:ScriptManager>
        <asp:HiddenField ID="hid" runat="server" />
        <asp:HiddenField ID="CurrentPage" runat="server" />
        <asp:HiddenField ID="Pages" runat="server" />
        <div id="dvText">
        </div>
        <br />
        <article id="module" class="module width_3_quarter" onscroll="GetScrollerEndPoint()">

   <header><h3 class="tabs_involved">Online Music Store</h3>
   
   </header>
   <asp:Button ID="btnForward" runat="server" CssClass="hiddenButton" onclick="btnForward_Click" />
   <asp:Button ID="btnBack" runat="server" CssClass="hiddenButton" onclick="btnBack_Click" />
   <asp:Repeater id="cdcatalog" runat="server"  >
               <HeaderTemplate>
    <table class="tablesorter" cellspacing="0"> 
   <thead> 
   <tr> 
       <th width="10%"> </th> 
       <th width="18%">Title</th> 
       <th width="18%">Artist</th> 
       <th width="18%">Country</th> 
       <th width="18%">Company</th> 
       <th width="18%">Price</th> 
   </tr> 
   </thead> 
   </table>
                </HeaderTemplate>

                <ItemTemplate>
    <table class="tablesorter" cellspacing="0"> 
   
   <tbody> 
   <tr> 
       <td width="5%"> <input type="checkbox" class="chkBoxClass"></td> 
       <td width="18%"><asp:Label ID="lblTitle" CssClass="title" runat="server" Text=<%# Bind("title") %>></asp:Label>  </td> 
       <td width="18%"><asp:Label ID="lblArtist" CssClass="artist" runat="server" Text=<%# Bind("artist") %>></asp:Label>
       </td > 
       <td width="18%">
       <asp:Label ID="lblCountry" runat="server" CssClass="country" Text=<%# Bind("country") %>></asp:Label>
       </td> 
       <td width="18%"><asp:Label ID="lblCompany" CssClass="company" runat="server" Text=<%# Bind("company") %>></asp:Label>
       </td> 
       <td width="18%"> 
       <asp:Label ID="lblPrice" runat="server" CssClass="price" Text=<%# Bind("price") %>></asp:Label></td>
       <td width="13%"><input type="image" src="images/icn_edit.png" onclick="return showModal()" title="Edit"><input type="image" src="images/icn_trash.png" title="Trash"></td> 
   </tr> 
   
   </tbody> 
   </table>
                </ItemTemplate>
                

               
               </asp:Repeater>

   </article>
        </form>
    </body>

    </html>

Step Three : Open the DataService.asmx and paste the following code

using System.Xml.Linq;
using System.IO;
using System.Data;
using System.Web.UI.WebControls;

/// <summary>
/// Summary description for DataService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
 [System.Web.Script.Services.ScriptService]
public class DataService : System.Web.Services.WebService {

    public DataService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string GetSongs() {

        

        DataSet ds = new DataSet(),dsToReturn;
        ds.ReadXml(Server.MapPath("~/XMLFile.xml"));
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = ds.Tables[0].DefaultView;
        pds.PageSize = 10;        
        pds.AllowPaging = true;
        pds.CurrentPageIndex = Convert.ToInt32(HttpContext.Current.Request.QueryString["pageIndex"]);

        dsToReturn = new DataSet();
        dsToReturn.Tables.Add(((DataView)pds.DataSource).ToTable());
        

        return dsToReturn.GetXml();
    }
    
}


Step Three : Running the Web Site

As you can see in the first image the Grid has some data loaded and scroll bar on the right side. As you scroll down and reach the end of the scroll bar, the "GetScrollerEndPoint" javascript function calls the "ajaxCalljavascript function to bring more data and to append it to the end of the grid.
















References : 
http://www.medialoot.com

Comments