How To Load Images Through Infinite Scroll In Asp.Net MVC Using JavaScript/Jquery

In this article, we are implementing/adding infinite scroll in ASP .NET MVC using JavaScript/Jquery. we are going to load images on scroll.
this way we can load only a few images at the time, and when the user scrolls down we are going to load another few images using javaScript. so our page will not get time to load.

please refer to the following steps for creating ASP .NET MVC application.

The above step will create an MVC application.

now, go to HomeController and add the following code into it.

public class ImagesViewVM
{
    public int ImagesViewId { get; set; }
    public string FileName { get; set; }
}

public static List<ImagesViewVM> imagesViewVMList = new List<ImagesViewVM>
{
    new ImagesViewVM
    {
        ImagesViewId=1,
        FileName="1.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=2,
        FileName="2.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=3,
        FileName="3.jpeg"
    },
    new ImagesViewVM
    {
        ImagesViewId=4,
        FileName="4.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=5,
        FileName="5.jpeg"
    },
    new ImagesViewVM
    {
        ImagesViewId=6,
        FileName="6.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=7,
        FileName="7.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=8,
        FileName="8.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=9,
        FileName="9.jpeg"
    },
    new ImagesViewVM
    {
        ImagesViewId=10,
        FileName="10.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=11,
        FileName="11.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=12,
        FileName="12.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=13,
        FileName="13.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=14,
        FileName="14.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=15,
        FileName="15.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=16,
        FileName="16.jpeg"
    },
    new ImagesViewVM
    {
        ImagesViewId=17,
        FileName="17.jpeg"
    },
    new ImagesViewVM
    {
        ImagesViewId=18,
        FileName="18.jpeg"
    },
    new ImagesViewVM
    {
        ImagesViewId=19,
        FileName="19.jpeg"
    },
    new ImagesViewVM
    {
        ImagesViewId=20,
        FileName="20.jpeg"
    },
    new ImagesViewVM
    {
        ImagesViewId=21,
        FileName="21.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=22,
        FileName="22.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=23,
        FileName="23.jpg"
    },
    new ImagesViewVM
    {
        ImagesViewId=24,
        FileName="24.jpg"
    }
};

public ActionResult Index()
{
    return View();
}

[HttpPost]
public JsonResult GetImages(int pageNumber, int pageSize)
{
    JsonResult result = new JsonResult();
    try
    {
        pageNumber = pageNumber - 1;

       var CertificateList = imagesViewVMList.Skip(pageNumber * pageSize).Take(pageSize).ToList();
        bool NoMoredata = false;
        if (CertificateList.Count() <= 0)
        {
            NoMoredata = true;
        }
        result = this.Json(new
        {
            IsSuccess = true,
            data = CertificateList,
            NoMoreData = NoMoredata
        }, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        return Json(new { IsSuccess = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
    }
    return result;
}

in above code, I define one ImagesViewVM class, and one static list named imagesViewVMList of ImagesViewVM class.in that list I store images detail. if you are going to retrieve it from the database then you don’t need to create this static list.

I have created one method named GetImages with two parameters pageNumber and pageSize.we are going to call this function from javascript using ajax call. this method will return the JSON response. here I used a static list, you can retrieve data from your database and make a response accordingly.

this method will return the data page wise and size which we passed in parameter.

now goto Index.cshtml, and add the following code into it.

@{
    ViewBag.Title = "Home Page";
}

<style>
    .loading {
        color: red;
        text-align: center;
    }

    #loading {
        display: none;
        color: red;
        font-size: 30px;
        text-align: center;
    }
</style>

<div class="jumbotron">
    <h1>Infinite Scroll</h1>
</div>

<div class="row" id="DivImages">



</div>

<div class="row text-center" style="padding-top:20px;" id="DivLoading"> <span id="loading">Loading Please wait...</span> </div>


@section scripts
{

    <script>

        var currentPage = 1;
        var PageSize = 6;
        var NoMoreData = false;

        $(document).ready(function () {
            
            loadPageData(currentPage);

            $(window).scroll(function () {

                if ($(window).scrollTop() > (Number($("#DivImages").height()) / 2) && !NoMoreData) {
                    //console.log("loading");
                    currentPage += 1;
                    loadPageData(currentPage);
                }

            });

        });



        function loadPageData(currentPageNumber) {
            $("#loading").show();

            $.ajax({
                url: '/Home/GetImages',
                method: 'post',
                dataType: "json",
                data: { pageNumber: currentPageNumber, pageSize: PageSize },
                success: function (Response) {
                    //console.log(Response);
                    if (Response.IsSuccess) {

                        var DivImages = $('#DivImages');
                        NoMoreData = Response.NoMoreData;

                        $(Response.data).each(function (index, ImagesData) {

                            var AppendDiv = '<div class="col-md-4"><div class="thumbnail" ><img src="/UploadedFiles/' + ImagesData.FileName + '" alt="file" class="img-responsive" style="width:100%;height:250px;"></div></div>';

                            DivImages.append(AppendDiv);


                        });


                    }
                    $("#loading").hide();
                },
                error: function (err) {
                    $("#loading").hide();
                    alert(err);
                }
            });
        }


    </script>

}

in view page, there is two DIV. with different ids DivImages, DivLoading.one for appending images into it, and one for showing loading text.
we need to define three global variables currentPage, PageSize, NoMoreData. in currentPage we need to set the first page, in PageSize we need to give how many images you want to load at a time, in NoMoreData first you need to set it at false once all data are loaded we will make it true so we will not make any ajax call after all data are loaded.

in document ready function, first, we need to call loadPageData function with currentPage. so it will load the few images on the document ready.

$(window).scroll(function () {}); function will called everytime when user scrolls. it will check that if scroll top position is more then half-height of image div and also there is NoMoreData is false then it will increase the currentPage number and call loadPageData function.

loadPageData function will do ajax call and in response, it will add/Append HTML into DivImages DIV.before every call it shows DivLoading DIV. and afterload finishes it hides DivLoading DIV.

The following is the output of the above code.

Submit a Comment

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

Subscribe

Select Categories