Infinite scroll using AngularJS in Asp.net MVC

Here I will Explain Infinite scroll pagination using AngularJS in Asp.net MVC. This technique generally used in Facebook and Twitter websites for data loading.

Introduction:

Today in this article, I will explain Infinite scroll using AngularJS in Asp.net MVC. In this example, I have used Ado.Net for database operation and Angular2. 

In the previous article, I have explained Server side pagination using AngularJs in 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. The infinite/unlimited scroll is while we scroll down our web page it’ll automatically load next paged data.

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. The infinite/unlimited scroll is while we scroll down our web page it’ll automatically load next paged data.

Follow these steps in order to implement “Infinite scroll using AngularJS in 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 the Infinite scroll.

CREATE TABLE [dbo].[tbl_registration] (

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

    [Email]    NVARCHAR (100) NULL,

    [Password] NVARCHAR (MAX) NULL,

    [Name]     VARCHAR (MAX)  NULL,

    [Address]  NVARCHAR (MAX) NULL,

    [City]     NVARCHAR (MAX) NULL,

    CONSTRAINT [PK_tbl_registration] PRIMARY KEY CLUSTERED ([Sr_no] ASC)

);

 

Now create store procedure for Infinite scroll

Create proc Sp_Get_data

@Pageindex int,

@Pagesize int

as

begin

Select * from tbl_registration order by Sr_no desc Offset @Pagesize*(@Pageindex-1) Rows Fetch next @Pagesize rows only

Select Count(Email) as totalcount from tbl_registration

end

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

 

Step3: Add Connection string in web.config file

Here I have added 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 model class

Now I have to create two class ‘register.cs’ and ‘regsiterlist.cs’ for display record and infinite scroll.

Go to Solutions Explorer > right click on Model> Add New class > Enter a class name (Here I rename it as ‘register.cs’).

Write all properties in ‘register.cs’ class as shown below

 

namespace Lazyloading.Models

{

    public class register

    {

        public int Sr_no { get; set; }

        public string  Email { get; set; }

        public string Password { get; set; }

        public string Name { get; set; }

        public string Address { get; set; }

        public string City { get; set; }

 

    }

}

 

In a similar way, add one more class as regsiterlist.cs to get the data and total count, as shown below.

 

namespace Lazyloading.Models

{

    public class regsiterlist

    {

        public List<register> registerdata { get; set; }

        public int totalcount { get; set; }

    }

}

 

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_layer’) > right click on folder > Add new class.

Now write the following code snippet given below.

using Lazyloading.Models;

using System;

using System.Collections.Generic;

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

using System.Linq;

using System.Web;

 

namespace Lazyloading.Database_Access_layer

{

    public class db

    {

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

        registerlist reglist = new registerlist();

        public registerlist Lazy_data(int pagesize, int pageindex)

        {

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

            com.CommandType = CommandType.StoredProcedure;

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

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

            con.Open();

            SqlDataReader dr = com.ExecuteReader();

            List<register> rslist = new List<register>();

            while (dr.Read())

            {

                register rs = new register();

                rs.Sr_no = Convert.ToInt32(dr["Sr_no"]);

                rs.Email = dr["Email"].ToString();

                rs.Password = dr["Password"].ToString();

                rs.Name = dr["Name"].ToString();

                rs.Address = dr["Address"].ToString();

                rs.City = dr["City"].ToString();

                rslist.Add(rs);

            }

            dr.NextResult();

            while (dr.Read())

            {

                reglist.totalcount = Convert.ToInt32(dr["totalcount"]);

            }

            reglist.registerdata = rslist;

            return reglist;

        }

    }

}

 

Inside this class, we are using ADO.NET for database operation and retrieve all information and the total count of the record.

 

Step6: Add Jsonresult GET methods in the controller for getting the record from Lazy_data method.

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.Data;

using Lazyloading.Models;

namespace Lazyloading.Controllers

{

    public class HomeController : Controller

    {

        registerlist rslist = new registerlist();

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

        public JsonResult Get_data(int page)

        {

            rslist = dblayer.Lazy_data(10, page);

            return Json(rslist, JsonRequestBehavior.AllowGet);

        }

 

    }

}

 

In the code given above, I have used the parameter as ‘page’ for getting the record on basis of page number and here 10 is the total number of record fetch.

 

Step8: Add New JS file for AngularJS Controller and AngularJS library file

Go to Solution Explorer > Right Click on the folder (where you want to save your AngularJS controller JS files, here I have created a folder named "AngularController"  under Resource Folder) > Add > Select Javascript file > Enter a name(I have to name as lazyload.js) > Add.

 Now we write following code snippet into lazyload.js

var app = angular.module('myapp', []);

 

app.controller("lazycontroller", function ($scope, $http) {

    $scope.currentpage = 1;

    $scope.totalpage = 0;

    $scope.detailslist = [];

 

    function getdata(page) {

        debugger;

        $scope.Isloading = true;

        $http.get("/Home/Get_data?page=" + page).then(function (response) {

            angular.forEach(response.data.registerdata, function (value) {

                $scope.detailslist.push(value);

            });

            $scope.totalpage = response.data.totalcount;

            $scope.Isloading = false;

        }, function (error) {

            $scope.Isloading = false;

            alert('Failed');

        })

    }

 

    getdata($scope.currentpage);

 

    $scope.Nextpage = function () {

        if ($scope.currentpage < $scope.totalpage) {

            $scope.currentpage += 1;

            getdata($scope.currentpage);

        }

    };

});

 

app.directive('infinitescroll', function () {

    debugger;

    return {

        restrict: 'A',

        link: function (scope,element,attrs) {

            element.bind('scroll', function () {

                if ((element[0].scrollTop + element[0].offsetHeight) == element[0].scrollHeight) {

                    scope.$apply(attrs.infinitescroll);

                }

 

            })

        }

    }

})

In the code given above, I have added a directive (here "infinitescroll") for check the scroll position and fired an AngularJS method for load new content (if available) while scroll reached to end of the existing content.

Step9:  Add new action into the controller for display data from the database.

 Here I have added ‘Index’ into ‘HomeController’. I have following code.

 public ActionResult Index()

        {

            return View();

        }

 

Step10: Add view for action in controller & design.

Right Click on Action Method > Add View > Enter View Name > 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>

</head>

<body>

    <div class="container">

        <h2>Infinity scroll in AngularJS</h2>

        <div ng-app="myapp" ng-controller="lazycontroller">

            <div style="position:relative">

                <span ng-show="Isloading" class="loading">Loading...</span>

                <div infinitescroll="Nextpage()" style="height:400px; overflow:auto;">

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

                        <thead>

                            <tr>

                                <th>Name</th>

                                <th>Email</th>

                                <th>Country</th>

                                <th>City</th>

                            </tr>

                        </thead>

                        <tbody>

                            <tr ng-repeat="emp in detailslist">

                                <td>{{emp.Email}} {{emp.Password}}</td>

                                <td>{{emp.Name}}</td>

                                <td>{{emp.Address}}</td>

                                <td>{{emp.City}}</td>

                            </tr>

                        </tbody>

                    </table>

                </div>

            </div>

        </div>

    </div>
    @* JS *@

    <script src="~/Resource/angular.min.js"></script>

    <script src="~/Resource/AngularController/lazyload.js"></script>

    @* CSS *@

    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

    <style type="text/css">

        /*Loading panel css*/

        .loading {

            position: absolute;

            left: 48%;

            top: 48%;

            display: block;

            padding: 5px;

            background-color:green;

            color: red;

            border: 1px solid;

            margin: 0 auto;

        }

    </style>

</body>

</html>

 

 

Step 11: Run Application.

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