asp.net MVC

infinite scroll jquery example

infinite scroll jquery example, someone asked me to explain?

In this article, I will show you how to add infinite scroll load content while scrolling with jQuery Ajax using asp.net MVC without using third party plugins. On scroll event jQuery call GetData() function and return records as a json format using JsonResult.

Here I am using Northwind database. You can download it from following link.

Download Northwind Database

Open Microsoft sql management studio and right click on the database and attach it.

Create an ado.net entity data model using table Customer and generate entity for that.

Step 1:

Create an asp.net mvc application and add a home controller. Copy and paste the following code.

  public ActionResult Index()
        {
            return View();
        }
 
        public JsonResult GetData(int pageIndex, int pageSize)
        {
            System.Threading.Thread.Sleep(3000);
            models db = new models();
            var products = (from product in db.Products.AsEnumerable()
                            select new
                            {
                                Name =product.ProductName,
                                UnitPrice =product.UnitPrice,
                                QuantityPerUnit =product.QuantityPerUnit
                           }).Distinct().ToList();
 
            var query = (from c in db.Customers
                        orderby c.CompanyName ascending
                         select new
                           {
                                Name =c.CompanyName,
                                Address =c.Address,
                                City = c.City,
                                Country =c.Country,
                                PostalCode = c.PostalCode,
                            })
                         .Skip(pageIndex *pageSize)
                         .Take(pageSize);
 
            return Json(query.ToList(), JsonRequestBehavior.AllowGet);        }

Step 2:

Create index view in the home controller and Copy and paste the following code. 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">

   var pageSize = 10;
    var pageIndex = 1;
    $(document).ready(function () {
        GetData();
 

       $(window).scroll(function () {
            if ($(window).scrollTop() ==
               $(document).height() -$(window).height()) {
                GetData();
            }
       });
   });
 
    function GetData() {
        $.ajax({
            type: 'GET',
            url: '/Customer/GetData',
            data: { "pageindex":pageIndex, "pagesize": pageSize },
            dataType: 'json',
            success: function (data) {
                debugger;
                if (data != null) {
                    for (var i = 0; i < data.length;i++) {
                        $("#container").append("<h2> " +
                            data[i].Name + "</h2>" +
                            "<p><i>" + data[i].Address + "</i></p><p><i>" +
                            data[i].City +data[i].Country + "- " + data[i].PostalCode + "</i></p>"
                            );
                    }
                    pageIndex++;
                }
            },
            beforeSend: function () {
                $("#progress").show();
            },
            complete: function () {
                $("#progress").hide();
            },
            error: function () {
                alert("Error while retrieving data!");
            }
        });
    }
</script>
 
<h2>Customer details</h2>
<div id="container"></div>
<div id="progress" style="display: none">
    <h4>Loading...</h4>
</div>

 

The GetData() function has two parameters, pageIndex and pageSize in the home controller, pageIndex is incremented for every ajax call method. On the page load, Ajax jQuery function calls the server side and fetches the records and displayed in JSON format. If the user scrolls the web page window.scroll() event will fire and retrieve the next set of records until the bottom of the Scroll region. 

The progress bar (page loading indicator) will show and hide using jQuery methods beforesend and comple callbacks.  

Page scroll jQuery demo:

load data on scroll using jquery

Post your comments / questions