Jul 22, 2015

Load Data while Scrolling Page Down with jQuery and ASP.Net MVC

This post is about Facebook style data loading while scrolling down the page. To identify the page scroll down, you can use the following snippet.

$(window).scroll(function () {
    if ($(window).scrollTop() == $(document).height() - $(window).height()) {
        //This is an Ajax method which will fetch the data from server
        FetchDataFromServer();
    }
});
 
This condition will satisfy when user scroll down and reached the bottom of the page. This will invoke the Ajax get method, which will return JSON data from server. For rendering the JSON, I am using jsrender template-ing engine. Here is the complete implementation. I am not using any database for this sample.
Here is the server side (MVC controller)

public ActionResult FetchData(int pageIndex = 0)
{
    var posts = new List<Post>();
    int first = pageIndex + 1;
    int last = pageIndex + 10;
    for (int i = first; i <= last; i++)
    {
        posts.Add(new Post()
        {
            Id = i,
            Date = DateTime.UtcNow,
            Content = "Content from Database with Id" + i,
            Title = "Title " + i
        });
    }

    return Json(posts, JsonRequestBehavior.AllowGet);
}
Client side (JQuery and JSRender)
$(function () {
    FetchDataFromServer();
    $(window).scroll(function () {
        if ($(window).scrollTop() ==
            $(document).height() - $(window).height()) {
            if ($('#loadMessage').css('display') == 'none') {
                FetchDataFromServer();
            }
        }
    });
});

function FetchDataFromServer() {
    $("#loadMessage").toggle();
    var id = $(".post:last").attr("id");
    $.ajax("/Home/FetchData", {
        type: "GET",
        contentType: "application/json",
        data: { pageIndex: id },
        dataType: "json",
        success: function (data) {
            var postsTemplate = $.templates("#posts");
            var html = postsTemplate.render(data);
            $(".post:last").after(html);
            $("#loadMessage").toggle();
        },
        error: function () {
            $("#loadMessage").toggle();
        }
    });
}
 
And here is the HTML part.

<div id="result">
    <div id="0" class="post"></div>
    <div id="loadMessage" style="display:none;">
        <img src="~/Content/loader.gif" />
    </div>
</div>
And here is the JSRender template
<script type="text/x-jsrender" id="posts">
    <div id="{{:Id}}" class="post">
        <h2>{{:Title}}</h2>
        <hr />
        <div>
            {{:Content}}
        </div>
    </div>
</script>
For identifying the Page, I am using the Div Id. If you don’t want that approach you can create a hidden variable and can do the same.

No comments:

Post a Comment