Implement Paging and Sorting using AngularJS in ASP.Net

Last Reply 8 months ago By dharmendr

Posted 8 months ago

How to implement paging and sorting in angularjs in asp.net

You are viewing reply posted by: dharmendr 8 months ago.
Posted 8 months ago Modified on 8 months ago

Hi rani,

Check this example. Now please take its reference and correct your code.

You can merge code from below links to acheive this.

Implement Table Sorting on Header click using AngularJS in ASP.Net

Implement Table Paging (Pagination) using AngularJS in ASP.Net

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

HTML

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" />
<script type="text/javascript" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.3.0.min.js"></script>
<script type="text/javascript">
    var app = angular.module('MyApp', ['ui.bootstrap']);
    app.controller("MyController", function ($scope, $http, $window) {
        $http.post("Default.aspx/GetEmployees", { headers: { 'Content-Type': 'application/json'} })
            .then(function (response) {
                $scope.Employees = eval(response.data.d);
                $scope.curPage = 1;
                $scope.itemsPerPage = 4;
                $scope.maxSize = 5;
                $scope.numOfPages = function () {
                    return Math.ceil($scope.Employees.length / $scope.itemsPerPage);
                };
                $scope.$watch('curPage + numPerPage', function () {
                    var begin = (($scope.curPage - 1) * $scope.itemsPerPage),
                    end = begin + $scope.itemsPerPage;
                    $scope.PagerEmployees = $scope.Employees.slice(begin, end);
                });

                // Default SortColumn.
                $scope.SortColumn = "EmployeeId";
                $scope.ReverseSort = false;

                $scope.SortData = function (column) {
                    $scope.ReverseSort = ($scope.SortColumn == column) ? !$scope.ReverseSort : false;
                    $scope.SortColumn = column;
                }

                $scope.GetSortClass = function (column) {
                    if ($scope.SortColumn == column) {
                        return $scope.ReverseSort ? 'arrow-down' : 'arrow-up';
                    }
                    return '';
                }
            }, function error(response) { alert(response.responseText); });
    });
</script>
<div ng-app="MyApp" ng-controller="MyController">
    <table class="table table-table-responsive">
        <thead>
            <tr>
                <th ng-click="SortData('EmployeeId')" style="width: 30px">
                    Id&nbsp;<div ng-class="GetSortClass('EmployeeId')">
                </th>
                <th ng-click="SortData('FirstName')" style="width: 100px">
                    First Name&nbsp;<div ng-class="GetSortClass('FirstName')">
                </th>
                <th ng-click="SortData('LastName')" style="width: 100px">
                    Last Name&nbsp;<div ng-class="GetSortClass('LastName')">
                </th>
                <th ng-click="SortData('City')" style="width: 100px">
                    City&nbsp;<div ng-class="GetSortClass('City')">
                </th>
                <th ng-click="SortData('Country')" style="width: 70px">
                    Country&nbsp;<div ng-class="GetSortClass('Country')">
                </th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="employee in PagerEmployees | orderBy:SortColumn:ReverseSort">
                <td>{{ employee.EmployeeId }}</td>
                <td>{{ employee.FirstName }}</td>
                <td>{{ employee.LastName }}</td>
                <td>{{ employee.City }}</td>
                <td>{{ employee.Country }}</td>
            </tr>
        </tbody>
    </table>
    <div align="center" data-pagination="" data-num-pages="numOfPages()" data-current-page="curPage"
        data-max-size="maxSize" data-boundary-links="true">
    </div>
</div>

CSS

<style type="text/css">
    /*Displays UP arrow*/
    .arrow-up
    {
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-bottom: 10px solid red;
        display: inline-block;
    }
        
    /*Displays DOWN arrow*/
    .arrow-down
    {
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-top: 10px solid red;
        display: inline-block;
    }
</style>

Namespaces

C#

using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;

VB.Net

Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Script.Serialization
Imports System.Web.Services

Code

C#

[WebMethod]
public static string GetEmployees()
{
    List<object> employees = new List<object>();
    string sql = "SELECT * FROM Employees";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    employees.Add(new
                    {
                        EmployeeId = sdr["EmployeeID"],
                        FirstName = sdr["FirstName"],
                        LastName = sdr["LastName"],
                        City = sdr["City"],
                        Country = sdr["Country"]
                    });
                }
            }
            conn.Close();
        }
    }

    return (new JavaScriptSerializer().Serialize(employees));
}

VB.Net

<WebMethod()>
Public Shared Function GetEmployees() As String
    Dim employees As List(Of Object) = New List(Of Object)()
    Dim sql As String = "SELECT * FROM Employees"
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand(sql)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    employees.Add(New With {
                        .EmployeeId = sdr("EmployeeID"),
                        .FirstName = sdr("FirstName"),
                        .LastName = sdr("LastName"),
                        .City = sdr("City"),
                        .Country = sdr("Country")
                    })
                End While
            End Using

            conn.Close()
        End Using
    End Using

    Return (New JavaScriptSerializer().Serialize(employees))
End Function

Screenshot

Or you can use of angular dir-paginate directive.

Check this example. Now please take its reference and correct your code. The code will be same as in the above sample.

HTML

<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/angular-utils-pagination@0.11.1/dirPagination.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', ['angularUtils.directives.dirPagination']);
        app.controller('MyController', function ($scope, $http) {
            $scope.Employees = [];
            $http.post("Default.aspx/GetEmployees", { headers: { 'Content-Type': 'application/json'} }).success(function (response) {
                $scope.Employees = eval(response.d);
            });

            $scope.sort = function (keyname) {
                $scope.sortBy = keyname;
                $scope.reverse = !$scope.reverse;
            }
        });
    </script>
</head>
<body ng-app="MyApp" ng-controller="MyController">
    <div class="panel panel-primary">
        <div class="panel-body">
            <div>
                <div class="col-md-12">
                    <input type="text" ng-model="search" class="form-control" placeholder="Search keyword..">
                </div>
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th ng-click="sort('EmployeeId')">
                                Id <span class="glyphicon sort-icon" ng-show="sortBy=='EmployeeId'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}">
                                </span>
                            </th>
                            <th ng-click="sort('FirstName')">
                                First Name <span class="glyphicon sort-icon" ng-show="sortBy=='FirstName'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}">
                                </span>
                            </th>
                            <th ng-click="sort('LastName')">
                                Last Name <span class="glyphicon sort-icon" ng-show="sortBy=='LastName'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}">
                                </span>
                            </th>
                            <th ng-click="sort('City')">
                                City <span class="glyphicon sort-icon" ng-show="sortBy=='City'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}">
                                </span>
                            </th>
                            <th ng-click="sort('Country')">
                                Country <span class="glyphicon sort-icon" ng-show="sortBy=='Country'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}">
                                </span>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr dir-paginate="employee in Employees|orderBy:sortBy:reverse|filter:search|itemsPerPage:5">
                            <td>{{ employee.EmployeeId }}</td>
                            <td>{{ employee.FirstName }}</td>
                            <td>{{ employee.LastName }}</td>
                            <td>{{ employee.City }}</td>
                            <td>{{ employee.Country }}</td>
                        </tr>
                    </tbody>
                </table>
                <div align="center">
                    <dir-pagination-controls max-size="5" direction-links="true" boundary-links="true"></dir-pagination-controls>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Screenshot