Create Infinite Scroll Using C# and jQuery To Auto Load Data On Scroll

Infinite Scroll is an auto polling system in which large dataset is fetched in chunks from the data source on request basis, which is usually scroll to bottom of the page. In this tutorial we will be implementing infinite scroll using C# and jQuery.

Basis of working of infinite scroll is pretty simple and can be explained in three steps:

How Infinite Scroll Works

  1. On load fetch some data from the data source
  2. When user scrolls to the bottom of the page, trigger event to fetch additional data from the data source
  3. Stitch this additional data with the existing data.

Seems pretty simple, isn’t it. So, lets try building a page with infinite scroll using C# and jQuery.

Building Infinite Scroll Using C# and jQuery

In this project we will build a page listing listing numbers :P. On page load we will only display first 50 natural numbers and when user scrolls down we will fetch more data in chuck of 50.

Creating Controller For Handling Requests

First, create a MVC controller for handling requests. I have created two methods one for initial view and other one for sending additional data when requested.

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var initialStrings = GetData();
            return View(initialStrings);
        }
        
        public JsonResult GetMoreData(int endIndex)
        {
            return Json(GetData(endIndex), JsonRequestBehavior.AllowGet);
        }

        private IEnumerable<string> GetData(int startIndex = 0)
        {
            for (var i = 1; i <= 50; i++)
            {
                yield return (i + startIndex).ToString();
            }
        }   
    }

This controller has a method Index() which displays the first 50 numbers and a method GetMoreData which when called returns next 50 numerals.

Creating View To Display Numbers

@model IEnumerable<string>
@{
   ViewBag.Title = "Home Page"; 
}

<div id="dataTable">
@{    
   foreach(var entry in Model) {
     @Html.Raw(entry)
   }
}
</div>

@Html.Hidden("recordCount", 50);

Our view is pretty minimal. All it does is iterate over the collection of numbers and display each number is a separate paragraph. Also, it creates a hidden field named recordCound  which holds the number of records on page.

jQuery To Trigger Request On Scroll

Now, the  best part – We will bind an event with scroll of window which make a request to our controller method when user scrolls down to the bottom of page.

This code snippet is quite simple and straight forward. iF you want, you can also create a jQuery plugin for it which will take URL and closure function to handle request and stitching of data.

$(function () {
        $(window).scroll(function () {
            // ScrollTop -> Distance from top
            // window height -> Current visible window height
            // document height -> Complete document height
            if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
                $.ajax({
                    url: '/Home/GetMoreData',
                    data: { endIndex: $("#recordCount").val() },
                    method: 'Post',
                    success: function (response) {                        
                        for (var i = 0; i < response.length; i++) {
                            $("#dataTable").append("<p>" + response[i] + "</p>");
                        }

                        $("#recordCount").val(parseFloat($("#recordCount").val()) + 50);
                    }
                });
            }
        });
    });

This was all. Trying implementing it yourself. If you have any queries, feel free to post here.

Leave a Reply

Your email address will not be published. Required fields are marked *