AngularJS UI bootstrap pagination in ASP.NET MVC


In this article, I am going to explain you how to implement AngularJS UI bootstrap pagination in ASP.NET MVC.

Creating ASP.NET MVC Empty Application

Fisrt step is to create ASP.NET MVC empty application as shown below.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net mvc 5 application

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Selecting asp.net mvc 5 empty template

Now, a new project will be created as shown below.

Asp.net mvc 5 empty folder structure

Adding Models

Go to Models folder and add new class file Country.cs. Now replace all code with below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class Country
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string CityName { get; set; }
        public int TotalRecords { get; set; }
    }
}

Adding Data Access Layer

Create a Repository.cs class file in root directory of application. Add below code. Here, add one method GetAllCountry which will return list of country. Methods takes 2 parameter PageNo and PageSize to sort and fetch records from database.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using WebApplication1.Models;

namespace WebApplication1
{
    public class Repository
    {
        public IEnumerable<Country> GetAllCountry(int PageNo, int PageSize)
        {
            List<Country> countryList = null;
            try
            {
                using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
                {
                    countryList = new List<Country>();
                    SqlCommand cmd = new SqlCommand("uspAngularDemo" , con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue( "@PageNo", PageNo);
                    cmd.Parameters.AddWithValue( "@PageSize", PageSize);
                    con.Open();
                    SqlDataReader sdr = cmd.ExecuteReader();
                    while (sdr.Read())
                    {
                        Country c = new Country();
                        c.Id = Convert.ToInt32(sdr["Id"].ToString());
                        c.Name = sdr[ "Name"].ToString();
                        c.CityName = sdr[ "CityName"].ToString();
                        c.TotalRecords = Convert.ToInt32(sdr["TotalRecords"].ToString());
                        countryList.Add(c);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return countryList;
        }
    }
}

Creating Table

We will be using tblCountry table for database operation. Use below script to create table.

create table tblCountry
(
Id int primary key identity,
Name varchar(100),
CityName varchar(100)
)

Insert Data

Use below script to insert data into table. Below script will insert 50 records using loop.

declare @count int=1
while(@count<=10)
begin
 insert into tblCountry values('India','City'+cast(@count as varchar(20)))
 insert into tblCountry values('USA','City'+cast(@count as varchar(20)))
 insert into tblCountry values('UK','City'+cast(@count as varchar(20)))
 insert into tblCountry values('Australia','City'+cast(@count as varchar(20)))
 set @count=@count+1
end

Creating Procedure

Use below script to create procedure.

create procedure uspAngularDemo
@PageNo int,
@PageSize int
as
begin
 select Id,Name,CityName,(select count(Id) from tblCountry) as 'TotalRecords'
       from (
         select Id,Name,CityName ,row_number() over (order by id desc) as rowno from tblCountry
        ) temp WHERE rowno between ( (@PageNo-1)*@PageSize)+1 and @PageSize*@PageNo
end

Adding Controller

Next step is to add controller to application. Go to controller folder and add new empty controller named as Home controller. Replace all code with below code. First method is Index which will return index view and second method is GetCountryList which return json data which will be called from index view using ajax method with angularjs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetCountryList( int PageNo, int PageSize)
        {
            Repository obj = new Repository();
            IEnumerable<Country> Country = null;
            Country = obj.GetAllCountry(PageNo, PageSize);
            return Json(Country, JsonRequestBehavior.AllowGet);
        }
    }
}

Adding View

Now, right click on home controller index action method, add new view and name Index. Select Empty template and uncheck Use layout page and click on Add as shown below.

Addling index view

Now go to Views / Home folder, open Index.cshtml file and replace all code with below code.

Here, 1) angular.js can be downloaded from angular website.
2) ui-bootstrap-tpls-0.13.4.min.js can be downloaded from link provided below.
ui-bootstrap-tpls-0.13.4.min.js
In 3) myAngularScript.js file, we will write angular code.
In 4) myStyle.css file, we will write pagination and table css.

Index.cshtml Code:
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title> AngularJS UI bootstrap pagination in asp.net mvc </title>
    <!--Angularjs version 1.7.2-->
    <script src="~/Scripts/angular.js"></script>
    <!--download link is provided in above description -->
    <script src="~/Scripts/ui-bootstrap-tpls-0.13.4.min.js"></script>
    <!--write your custom code in myAngularScript.js file-->
    <script src="~/Scripts/myAngularScript.js"></script>
     <!--write css for pagination-->
    <link href="~/Content/myStyle.css" rel="stylesheet" />
</head>
<body ng-app="myApp" ng-controller="CountryCtlr">
    <table>
        <thead>
            <tr>
                <th> Id</th>
                <th> Country Name</th>
                <th> City Name</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="country in Country">
                <td> {{country.Id}}</td>
                <td> {{country.Name}}</td>
                <td> {{country.CityName}}</td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td align="left" colspan="3">
                    <pagination total-items="totalCount" ng-change="pageChanged()" items-per-page="pageSizeSelected"
                                direction-links="true" ng-model="pageIndex" max-size="maxSize" class="pagination"
                                boundary-links="true" rotate="false" num-pages="numPages">
                    </pagination>
                </td>
            </tr>
        </tfoot>
    </table>
</body>
</html>

Writing AngularJS Code in Custom JavaScript File

Now, we need to write custom javascript code in myAngularScript.js file and save in Scripts folder.

myAngularScript.js Code:
var app = angular.module('myApp', ['ui.bootstrap']);
app.controller('CountryCtlr', function ($scope, $http) {

    $scope.maxSize = 5;     // limit number for pagination display number.  
    $scope.totalCount = 0;  // total number of items in all pages. initialize as a zero 
    $scope.pageIndex = 1;   // current page number. first page is 1
    $scope.pageSizeSelected = 5; // maximum number of items per page. 

    $scope.GetCountryList = function () {
        $http.get('/Home/GetCountryList' , { params: { PageNo: $scope.pageIndex, PageSize: $scope.pageSizeSelected } }).then(
                       function (response) {
                           $scope.Country = response.data;
                           $scope.totalCount = response.data[0].TotalRecords;
                       },
                       function (err) {
                           alert(err);
                       });
    }
    //Loading country list on first time 
    $scope.GetCountryList();
    //this method is called on page change
    $scope.pageChanged = function () {
        $scope.GetCountryList();
    };
});

Use below css to style your pagination.

myStyle.css Code:
/*table css*/
table {
    border-collapse: collapse;
    width: 100%;
}

th, td {
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #f2f2f2;
}

th {
    background-color: #337ab7;
    color: white;
}
/*table css*/

/*pagination css*/
.pagination {
    display: inline-block;
    padding-left: 0;
    margin: 20px 0;
    border-radius: 4px;
}

    .pagination > li {
        display: inline;
    }

        .pagination > li > a,
        .pagination > li > span {
            position: relative;
            float: left;
            padding: 6px 12px;
            margin-left: -1px;
            line-height: 1.42857143;
            color: #337ab7;
            text-decoration: none;
            background-color: #fff;
            border: 1px solid #ddd;
        }

        .pagination > li:first-child > a,
        .pagination > li:first-child > span {
            margin-left: 0;
            border-top-left-radius: 4px;
            border-bottom-left-radius : 4px;
        }

        .pagination > li:last-child > a,
        .pagination > li:last-child > span {
            border-top-right-radius: 4px;
            border-bottom-right-radius : 4px;
        }

        .pagination > li > a:hover,
        .pagination > li > span:hover,
        .pagination > li > a:focus,
        .pagination > li > span:focus {
            z-index: 2;
            color: #23527c;
            background-color: #eee;
            border-color: #ddd;
        }

    .pagination > .active > a,
    .pagination > .active > span,
    .pagination > .active > a:hover,
    .pagination > .active > span:hover,
    .pagination > .active > a:focus,
    .pagination > .active > span:focus {
        z-index: 3;
        color: #fff;
        cursor: default;
        background-color: #337ab7;
        border-color: #337ab7;
    }

    .pagination > .disabled > span,
    .pagination > .disabled > span:hover,
    .pagination > .disabled > span:focus,
    .pagination > .disabled > a,
    .pagination > .disabled > a:hover,
    .pagination > .disabled > a:focus {
        color: #777;
        cursor: not-allowed;
        background-color: #fff;
        border-color: #ddd;
    }

.pagination-lg > li > a,
.pagination-lg > li > span {
    padding: 10px 16px;
    font-size: 18px;
    line-height: 1.3333333;
}

.pagination-lg > li:first-child > a,
.pagination-lg > li:first-child > span {
    border-top-left-radius: 6px;
    border-bottom-left-radius : 6px;
}

.pagination-lg > li:last-child > a,
.pagination-lg > li:last-child > span {
    border-top-right-radius: 6px;
    border-bottom-right-radius : 6px;
}

.pagination-sm > li > a,
.pagination-sm > li > span {
    padding: 5px 10px;
    font-size: 12px;
    line-height: 1.5;
}

.pagination-sm > li:first-child > a,
.pagination-sm > li:first-child > span {
    border-top-left-radius: 3px;
    border-bottom-left-radius : 3px;
}

.pagination-sm > li:last-child > a,
.pagination-sm > li:last-child > span {
    border-top-right-radius: 3px;
    border-bottom-right-radius : 3px;
}

.pager {
    padding-left: 0;
    margin: 20px 0;
    text-align: center;
    list-style: none;
}

    .pager li {
        display: inline;
    }

        .pager li > a,
        .pager li > span {
            display: inline-block;
            padding: 5px 14px;
            background-color: #fff;
            border: 1px solid #ddd;
            border-radius: 15px;
        }

            .pager li > a:hover,
            .pager li > a:focus {
                text-decoration: none;
                background-color: #eee;
            }

    .pager .next > a,
    .pager .next > span {
        float: right;
    }

    .pager .previous > a,
    .pager .previous > span {
        float: left;
    }

    .pager .disabled > a,
    .pager .disabled > a:hover,
    .pager .disabled > a:focus,
    .pager .disabled > span {
        color: #777;
        cursor: not-allowed;
        background-color: #fff;
    }
/*pagination css*/

Output can be seen as below after running application.

AngularJS UI bootstrap pagination in ASP.NET MVC


Share This


blog comments powered by Disqus