Monday, July 15, 2019

Infinite Scroll or Endless Scroll in ASP.NET or MVC

In this quick post I will show you how to develop infinite or endless scrolling on web pages. This feature is required on websites like blog, media, e-commerce etc. If you scrolling in twitter or Facebook feed you will notice new contents loads up automatically when scroller reaches at the end of the page/document.



Technically, when you reach at the end on horizontal scroll bar, it makes a new Ajax call to the database and response loads on web page every time. It looks technically little sound to implement but if you have Ajax working knowledge it is way easy than implementing good paging feature in your existing data control like DataList etc.

This is going to be same in ASP.NET Web Forms and MVC. Let’s follow the steps to implement it.

Step 1

Open the page where you want to create infinite scrolling and create following DIV element:

<div id="sectionArticles"></div>

We will append the Ajax data in this DIV every time.

Step 2

On the same page, care following DOM element/flag:

<input type="hidden" id="lastRowId" value="0" />

This is a hidden element, we will store our last row id on each Ajax call here. It will help us to find last row id in the next Ajax call, to load next data set.

Step 3

On the same web page or other .js file add following jQuery/JavaScript code:

<script>
    //get default articles
    $(document).ready(function () {
        GetArticlesFromNextSection(false);
    });

    //get next articles automatic
    $(window).scroll(function () {
        if ($(window).scrollTop() == $(document).height() - $(window).height()) {
            GetArticlesFromNextSection(true);
        }
    });

    //common handler
    function GetArticlesFromNextSection(scrollPage) {
        var lastRowId = ($("#lastRowId").val() * 1);
        var isHistoryBack = (lastRowId > 0 && !scrollPage);

        $.ajax({
            type: 'GET',
            url: '/Service/GetTopArticlesFromNextSection?lastRowId=' + lastRowId + '&isHistoryBack=' + isHistoryBack,
            dataType: 'json',
            success: function (jsonData) {
                var rowid = lastRowId + 1;

                if (jsonData == null) {
                    return;
                }

                $.each(jsonData, function (index, section) {
                    var sectionIndex = (isHistoryBack ? index + 1 : rowid);
                    var articleData = "";
                    $.each(section.SectionArticles, function (iindex, item) {
                        articleData += '<li>' +
                                   '<div class="imagebox"><img src="' + item.ImageUrl + '" alt="article image"/></div>' +
                                   '<div class="descriptionbox"><h4><a href="' + item.Url + '</a></h4>' +
                                   '<p>' + item.Summary + '</p>'
                        '</li>';
                    });
                    $('#sectionArticles').append(articleData);
                });

                if (!isHistoryBack) {
                    $("#lastRowId").val(rowid);
                }
            },
            error: function () {
                //alert('Error');
            }
        });

        return false;
    }
</script>

Remember to use the reference of jQuery library. You can keep above code in a separate .js file if you want.

In the above code, you will see three functions.

When documents loads, $(document).ready() fires up and call GetArticlesFromNextSection(false) function. It has false bool property, this instructs there is no history (no any article) on web page.

When you scroll all the way down on the web page $(window).scroll() fires up and calls the funtion GetArticlesFromNextSection(true), actually it fires up when scroll bar reaches at the end. It has true bool property, it instructs oh there is article already on the page, and it repeats each time scroll bar reaches at the end.

Now we have common GetArticlesFromNextSection(scrollPage) function. It will call service which returns Json data. This function creates DOM structure and appends to 'sectionArticles' and also sets the flag 'lastRowId'.

Inside common handler function you can use any GIF loading image, this way user will keep patience “oh it’s loading!”

Step 4

Here is our Ajax call handler, you can see I’m using Action Result and there is no any problem if you use this in Web Forms, all you need is MVC bits and class that inherits from Controller. I worked on several Web Form projects that uses this concept, it make developers life way easy.

public ActionResult GetTopArticlesFromNextSection(int lastRowId, bool isHistoryBack)
{
    var sectionArticles = BLL.SectionArticle.GetNextSectionTopArticles(lastRowId, isHistoryBack);
    return Json(sectionArticles, JsonRequestBehavior.AllowGet);
}

Also note I’m using another BLL for my business logic. You can write that logic right here in the ActionResult method and return Json response.

Hope this helps.

No comments:

Post a Comment