Server Side Paging using AngularJS dirPagination directive in ASP.Net MVC

Last Reply 5 months ago By dharmendr

Posted 5 months ago

Hi,

I have one table with relevant fields

I need to fetch those values to grid view

Currently my requirement is i need to load 10 records only by default

After clciking of 2nd page again i need to call method in controller then only i need to display remaining 10 records like that i am going to do n no pages in grid view

so every time i need to call method in controller code after clciking of page number in grid view

Note:In my code it was loading at a time database values i don't need like that

my Final requirement is based upon only pagenumber i need to call method in controller.

https://ibb.co/S0d4sF3

Could you please check my code and help me 

@{ 
    Layout = null;
}
<html>
<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
    <script src="~/scripts/dirpagination.js"></script>
    <script>
        var app = angular.module('invoice', ['angularUtils.directives.dirPagination']);
        app.controller('InvoiceController', ['$scope', '$http', '$window', 'RegistrationService', function ($scope, $http, $window, RegistrationService) {
            GetAllEmployees();
            //To Get All Records
            function GetAllEmployees() {
                var getData = RegistrationService.getEmployees();
                getData.then(function (emp) {
                    $scope.employees = emp.data;
                }, function (emp) {alert("Records gathering failed!");});
            }
        }]);
        app.service("RegistrationService", function ($http) {
            //get All Employee
            this.getEmployees = function () {
                return $http.get("/serversidepagination/getAll");
            };
        });
    </script>

</head>
<body ng-app="invoice" ng-controller="InvoiceController">
    <div id="dvContainer">
        <div>
            <div class="table-responsive ">
                <table id="dvData" cellpadding="12" class="table table-bordered table-hover table-striped" >
                    <tr class="success">
                        <th>Code</b</th>
                        <th><b>Name</b></th>
                        <th><b>Description</b>  </th>
                        <th><b>Active</b></th>
                    </tr>
                    <tr dir-paginate="employee in employees |orderBy:sortKey:reverse|filter:search|itemsPerPage:10" ng-model="search">
                        <td><input type="hidden" ng-model="employee.Id" />{{employee.Code}}</td>
                        <td>{{employee.Name }}</td>
                        <td>{{employee.Description}}</td>
                        <td><input type="checkbox" ng-model="employee.Active" /></td>
                    </tr>
                    <b style="color: #5bc0de; margin-left: 20px;">Total Records </b>:
                    <b>{{employees.length}}  </b>
                </table>
            </div>
        </div>
    </div>
</body>
</html>

 

        public JsonResult getAll()
        {
            db.Configuration.ProxyCreationEnabled = false;
            var empList = (from TP in db.Employees
                               select new
                               {
                                   Id = TP.Id,
                                   Name = TP.Name,
                                   Code = TP.Code,
                                   Description = TP.Description,
                                   Active = TP.Active
                               }).ToList();

            var JsonResult = Json(empList, JsonRequestBehavior.AllowGet);
            JsonResult.MaxJsonLength = int.MaxValue;
            return JsonResult;
        }

 

Posted 5 months ago

Hi mahesh213,

With dirPagination directive it is not possible to load only those record having the pagenumber.

Refering the below article i have created an example.

ASP.Net MVC: Custom Paging in WebGrid using Stored Procedure and Entity Framework

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

For paging i have used ASPSnippets_Pager.

You can download the js from the sample provided in the link.

Database

I am making use of Microsoft's Northwind Database. You can download it from here.

Download and install Northwind Database

Namespaces

using System.Data.Objects;
using System.Linq;

Model

public class CustomerModel
{
    public List<Customer> Customers { get; set; }
    public int PageIndex { get; set; }
    public int PageSize { get; set; }
    public int RecordCount { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult PopulateCustomers(int pageIndex)
    {
        NorthwindEntities entities = new NorthwindEntities();
        CustomerModel model = new CustomerModel();
        model.PageIndex = pageIndex;
        model.PageSize = 10;
        ObjectParameter recordCount = new ObjectParameter("RecordCount", typeof(int));
        model.Customers = entities.GetCustomers(model.PageIndex, model.PageSize, recordCount).ToList();
        model.RecordCount = Convert.ToInt32(recordCount.Value);
        return Json(model, JsonRequestBehavior.AllowGet);
    }
}

View

<html>
<head>
    <title>Index</title>
    <style type="text/css">
        .Pager span
        {
            text-align: center;
            color: #333;
            display: inline-block;
            width: 20px;
            background-color: #B8DBFD;
            margin-right: 3px;
            line-height: 150%;
            border: 1px solid #B8DBFD;
            border-radius: 5px;
        }
        
        .Pager a
        {
            text-align: center;
            display: inline-block;
            width: 20px;
            background-color: #ccc;
            color: #333;
            border: 1px solid #ccc;
            margin-right: 3px;
            line-height: 150%;
            text-decoration: none;
            border-radius: 5px;
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
    <script src="../../ASPSnippets_Pager.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', []);
        app.controller('MyController', ['$scope', '$http', '$window', 'RegistrationService', function ($scope, $http, $window, RegistrationService) {
            PopulateCustomers(1);
            $("body").on("click", ".Pager .page", function () {
                PopulateCustomers(parseInt($(this).attr('page')));
            });

            function PopulateCustomers(Index) {
                var getData = RegistrationService.GetCustomers(Index);
                getData.then(function (response) {
                    $scope.Customers = response.data.Customers;
                    $(".Pager").ASPSnippets_Pager({
                        ActiveCssClass: "current",
                        PagerCssClass: "pager",
                        PageIndex: response.data.PageIndex,
                        PageSize: response.data.PageSize,
                        RecordCount: response.data.RecordCount
                    });
                }, function (response) {
                });
            }
        } ]);

        app.service("RegistrationService", function ($http) {
            this.GetCustomers = function (index) {
                var response = $http({
                    method: "POST",
                    url: "/Home/PopulateCustomers",
                    params: { pageIndex: index }
                });
                return response;
            }
        });
    </script>
</head>
<body ng-app="MyApp" ng-controller="MyController">
    <table id="tblCustomers" cellpadding="0" cellspacing="0">
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>City</th>
            <th>Country</th>
        </tr>
        <tbody ng-repeat="m in Customers">
            <tr>
                <td>{{m.CustomerID}}</td>
                <td>{{m.ContactName}}</td>
                <td>{{m.City}}</td>
                <td>{{m.Country}}</td>
            </tr>
        </tbody>
    </table>
    <br />
    <div class="Pager">
    </div>
</body>
</html>

Screenshot


Posted 5 months ago

Hi mahesh213,

Refering the below article i have created an example.

ASP.Net MVC: Custom Paging in WebGrid using Stored Procedure and Entity Framework

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

Database

I am making use of Microsoft's Northwind Database. You can download it from here.

Download and install Northwind Database

SQL

CREATE PROCEDURE [dbo].[Customers_GetCustomersPageWise]  
	@PageIndex INT = 1,
	@PageSize INT = 20,
	@RecordCount INT OUTPUT
AS
BEGIN	
	SET NOCOUNT ON;

	SELECT  (ROW_NUMBER() OVER(Order By CustomerId)) AS RowNumber,
			[CustomerID]
			,[CompanyName]
			,[ContactName]
			,[ContactTitle]
			,[Address]
			,[City]
			,[Region]
			,[PostalCode]
			,[Country]
			,[Phone]
			,[Fax]
	INTO #Results	
	FROM [Customers]	

	SELECT @RecordCount = Count(*) FROM #Results

	SELECT * FROM #Results WHERE 
	ROWNUMBER BETWEEN  (@PageIndex-1)*@PageSize + 1 AND (((@PageIndex-1)*@PageSize + 1)+@PageSize)-1 OR @PageIndex = -1	

	DROP TABLE #Results
END

Model

public class CustomerModel
{
    public List<Customer> Customers { get; set; }
    public int TotalRecords { get; set; }
}

Namespaces

using System.Data.Objects;
using System.Linq;

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult GetCustomers(int PageNo, int PageSize)
    {
        NorthwindEntities entities = new NorthwindEntities();
        CustomerModel model = new CustomerModel();
        ObjectParameter recordCount = new ObjectParameter("RecordCount", typeof(int));
        model.Customers = entities.GetCustomersPageWise(PageNo, PageSize, recordCount).ToList();
        model.TotalRecords = Convert.ToInt32(recordCount.Value);
        return Json(model, JsonRequestBehavior.AllowGet);
    }
}

View

<html>
<head>
    <title>Index</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.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', ['$scope', '$http', '$window', function ($scope, $http, $window) {
            $scope.Customers = [];
            $scope.PageIndex = 1;
            $scope.RecordCount = 0;
            $scope.PageSize = 10;
            $scope.GetCustomers = function (index) {
                $scope.Customers = [];
                $http.get("/Home/GetCustomers/", { params: { PageNo: index, PageSize: $scope.PageSize} })
                .then(function (response) {
                    $scope.Customers = response.data.Customers;
                    $scope.RecordCount = response.data.TotalRecords;
                }).then(function (response) {
                });
            };
            $scope.GetCustomers($scope.PageIndex);
        } ]);
    </script>
</head>
<body ng-controller="MyController" ng-app="MyApp">
    <table class="table table-bordered table-hover table-striped">
        <thead>
            <tr class="success">
                <th>Id</th>
                <th>Name</th>
                <th>City</th>
                <th>Country</th>
            </tr>
        </thead>
        <tbody>
            <tr dir-paginate="customer in Customers|itemsPerPage:PageSize" total-items="RecordCount">
                <td>{{customer.CustomerID}}</td>
                <td>{{customer.ContactName}}</td>
                <td>{{customer.City}}</td>
                <td>{{customer.Country}}</td>
            </tr>
        </tbody>
    </table>
    <dir-pagination-controls max-size="PageSize" direction-links="true" boundary-links="true"
        on-page-change="GetCustomers(newPageNumber)">
    </dir-pagination-controls>
</body>
</html>

Screenshot