Infinite Scrolling Using JQuery Ajax in Asp.net MVC

Here I will explain how to perform Infinite scrolling using JQuery Ajax in Asp.net means we load dynamically on scroll of page.

Introduction:

Today in this article, I will explain Infinite scroll using JQuery Ajax in Asp.net MVC means to load data dynamically on page scroll using JQuery Ajax and Asp.net MVC

Many Web applications such as Facebook and Twitter use a technique known as infinite scrolling or endless scrolling wherein data is loaded on the fly when a user scrolls to the bottom of a web page.  Infinite Scroll is a web design technique that prevents the browser scroll bar from scrolling to the bottom of the page, causing the page to grow with additional content instead.

I already discuss Infinite scroll using AngularJS in Asp.net MVC in the previous article.

Follow these steps in order to implement “Infinite scrolling using Jquery Ajax and Asp.net MVC”

Step1: Create New Project.

 Go to File > New > Project > Web > Asp.net MVC web project > Enter Application Name > Select your project location > click to add button > It will show new dialog window for select template > here we will select empty project > then click to ok

Step2: Create a table and Stored procedure in the database.

In this example, I have used following table for infinite scrolling and load data.

CREATE TABLE [dbo].[employee] (

    [id]      INT            IDENTITY (1, 1) NOT NULL,

    [name]    NVARCHAR (50)  NULL,

    [email]   NVARCHAR (MAX) NULL,

    [address] NVARCHAR (MAX) NULL,

    CONSTRAINT [PK_employee] PRIMARY KEY CLUSTERED ([id] ASC)

);

 

Now create store procedure for Infinite scroll

 Create proc Sp_Employee_LazyLoad

@PageIndex int,

@PageSize int

as

begin

Select * from employee order by id asc offset @PageSize*(@PageIndex-1) Rows fetch next @PageSize rows only

end

 Run above script in MS SQL Server and click to execute button

 

Step3: Add Connection string in web.config file

 Here I have to add connection string in ‘web.config’ file under Configuration section as follows

<connectionStrings>

    <add name="con" connectionString="Data Source=.;Initial Catalog=test;Integrated Security=True" providerName="System.Data.SqlClient"/>

  </connectionStrings>

 

Step4: Create a controller.

Go to Solutions Explorer > right click on controller folder > Add Controller > Enter Controller name > Select template “empty MVC Controller   ” > Add.

Here I have created a controller “HomeController”

Now we will add a view for Index action where we will perform infinite scroll.

 

Step5: Create a class for Database operation.

Here in this example, I have used Ado.net as database operation so we need to create a class for all database operations. Here I have created ‘db.cs’ class.

Go to Solutions Explorer > right click on project solution> Add New Folder > Enter Folder name (Here I rename it as ‘database_Access’) > right click on folder > Add new class.

Now write the following code snippet given below.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data.SqlClient;

using System.Data;

using System.Configuration;

namespace InfiniteJquery.Database_Access

{

    public class db

    {
       public class employee

       {
           public int id { get; set; }

        public string name  { get; set; }

        public string email { get; set; }

        public string address { get; set; }

       }

      
        public static List<employee> GetEmployee(int pageindex,int pagesize)

       {

           SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);

           SqlCommand com = new SqlCommand("Sp_Employee_LazyLoad", con);

           com.CommandType = CommandType.StoredProcedure;

           com.Parameters.AddWithValue("@PageIndex", pageindex);

           com.Parameters.AddWithValue("@PageSize", pagesize);

           List<employee> listemp = new List<employee>();

 

           SqlDataAdapter da = new SqlDataAdapter(com);

           DataSet ds = new DataSet();

           da.Fill(ds);

           foreach (DataRow dr in ds.Tables[0].Rows)

           {

               listemp.Add(new employee

               {

                   id=Convert.ToInt32(dr["id"]),

                   name=dr["name"].ToString(),

                   email = dr["email"].ToString(),

                   address = dr["address"].ToString()

               });

           }

           return listemp;

       }

    }
}

This part is very similar to the paging task. Here pageindex is block number that we call from view and pagesize is number total number of record call on every request.

 

Step6: Add methods in the controller.

Here I have created following methods in HomeController, that has following code snippet:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.IO;

using InfiniteJquery.Database_Access;

namespace InfiniteJquery.Controllers

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

        Database_Access.db dblayer = new Database_Access.db();

        public ActionResult Index()

        {

            int pagesize = 20;

            var rowdata = db.GetEmployee(1, pagesize);

            return View(rowdata);

        }

 

        protected string renderPartialViewtostring(string Viewname,object model)

        {

            if (string.IsNullOrEmpty(Viewname))

           

                Viewname = ControllerContext.RouteData.GetRequiredString("action");

                ViewData.Model = model;

                using (StringWriter sw = new StringWriter())

                {

                    ViewEngineResult viewresult = ViewEngines.Engines.FindPartialView(ControllerContext, Viewname);

                    ViewContext viewcontext = new ViewContext(ControllerContext, viewresult.View, ViewData, TempData, sw);

                    viewresult.View.Render(viewcontext, sw);

                    return sw.GetStringBuilder().ToString();

                }

          

        }

 

        public class JsonModel

        {

            public string HTMLString { get; set; }

            public bool NoMoredata { get; set; }

        }

        [ChildActionOnly]

        public ActionResult table_row(List<db.employee> Model)

        {

            return PartialView(Model);

        }

        [HttpPost]

        public ActionResult InfiniteScroll(int pageindex)

        {

            System.Threading.Thread.Sleep(1000);

            int pagesize = 20;

            var tbrow = db.GetEmployee(pageindex, pagesize);

            JsonModel jsonmodel = new JsonModel();

            jsonmodel.NoMoredata = tbrow.Count < pagesize;

            jsonmodel.HTMLString = renderPartialViewtostring("table_row", tbrow);

            return Json(jsonmodel);

        }

    }
}

 

In the code given above, InfiniteScroll is the POST method that called by view with parameter pageindex and renderpartialViewtostring is use to convert partial view(table_row) into string format

 

Step7: Add partial view design

 

Right Click on Action Method > Add View > Enter View Name(Here I add table_row) > Select View Engine (Razor) > Add.

This partial view has following code snippet,

@model List<InfiniteJquery.Database_Access.db.employee>

    @{

        foreach (var item in Model)

        {

            <tr>

                <td>@item.id</td>

                <td>@item.name</td>

                <td>@item.email</td>

                <td>@item.address</td>

            </tr>

        }

    }

 

Step8: Add view for action in controller & design.

Right Click on Action Method > Add View > Enter View Name (Here I add Index) > Select View Engine (Razor) > Add.

It has following code and design

@{

    Layout = null;

}

 

<!DOCTYPE html>

 

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

    <link href="~/Resource/bootstrap.min.css" rel="stylesheet" />

    <script src="~/Resource/jquery-1.7.1.min.js"></script>

</head>

<body>

    <div id="tblbody">

        <table class="table table-responsive table-striped table-bordered" id="tbldata">

            <thead>

                <tr>

                <th>ID</th>

                <th>Name</th>

                <th>Email</th>

                <th>Address</th>

                </tr>

            </thead>

            <tbody id="trow">

                @{

                    Html.RenderAction("table_row", "Home", new { Model = Model });

                }

            </tbody>

        </table>

        <div id="loadingdiv" style="text-align:center;display:none;margin-bottom:20px;">

            <img src="~/Resource/ajax-loader.gif" />

        </div>

    </div>

    <script>

        var pageindex = 2;

        var NoMoredata = false;

        var inProgress = false;

        $(window).scroll(function () {

            if ($(window).scrollTop() > Number($("#tblrow").height()) / 2 && !NoMoredata && !inProgress) {

              

                inProgress = true;

                $("#loadingdiv").show();

                $.post("@Url.Action("InfiniteScroll","Home")", { "pageindex": pageindex },

                    function (data) {

                        pageindex = pageindex + 1;

                        NoMoredata = data.NoMoredata;

                        $("#trow").append(data.HTMLString);

                        $("#loadingdiv").hide();

                        inProgress = false;

                    }

                    );

            }

        });

    </script>

</body>

</html>

 

When window scroll to half of tblrow div then I have to call function InfiniteScroll with parameter pageindex and then append that string into tbody

Step 9: Run Application.

We have done all steps, Now It’s time to run the application

 

If you have any problem and face any difficulty then Share your experiences with us in the comments below!

Like this post? Don’t forget to share it!