Custom Paging

Custom Paging improves the performance of default paging by retrieving only those records from the database that must be displayed on the particular page of data requested by the user. However, custom paging involves a bit more efforts to implement than that for default paging.

Read the below articles first to understand the AngularJS UI-Grid.

Prerequisites

Visual Studio 2017 is the prerequisite to work with this article.

Thus, let's just use the sections with which we can implement the functionality.

Create ASP.NET MVC 5 Application

In this section, we'll create an ASP.NET Web Application with the MVC 5 Project Template. Use the procedure given below.

Step 1

Open Visual Studio 2015 and click "New Project".

Step 2

Select "Web" from the left pane and create ASP.NET Web application.

Step 3

Select the MVC Project template in the next ASP.NET wizard.

Visual Studio automatically creates the MVC 5 Application, adds some files and folders to the solution.

Working with Entity Framework

Step 1

Right click on Models folder, click Add New Item, select ADO.NET Entity Data Model from Data template and give a name.

Step 2

Select EF Designer from the database.

Step 3

Make a new connection and select a connection, if you already have a connection.

Step 4

Select tables, view, and stored procedures and click Finish.

Stored Procedure

  1. USE [NORTHWND]
  2. GO
  3. /****** Object: StoredProcedure [dbo].[GetEmployeeWithPaging] Script Date: 11/13/2017 12:56:50 PM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. ALTER PROCEDURE [dbo].[GetEmployeeWithPaging]
  9. @PageNumber INT = NULL,
  10. @PageSize INT = NULL,
  11. @OrderBy VARCHAR(50) = N'EmployeeID', -- Column to sort programs by
  12. @SortDirection VARCHAR(4) = N'asc'
  13. AS
  14. DECLARE @totalCount int
  15. SET @totalCount = (SELECT COUNT(EmployeeID) as totalRecords FROM Employees)
  16. SELECT EmployeeID,
  17. FirstName,
  18. LastName,
  19. City,
  20. Region,
  21. PostalCode,
  22. Country,
  23. Notes,
  24. @totalCount as TotalCount
  25. FROM Employees
  26. ORDER BY
  27. CASE WHEN @SortDirection = 'asc' AND @OrderBy = 'FirstName' THEN FirstName END ASC
  28. ,CASE WHEN @SortDirection = 'desc' AND @OrderBy = 'FirstName' THEN FirstName END DESC
  29. ,CASE WHEN @SortDirection = 'asc' AND @OrderBy = 'LastName' THEN LastName END ASC
  30. ,CASE WHEN @SortDirection = 'desc' AND @OrderBy = 'LastName' THEN LastName END DESC
  31. ,CASE WHEN @SortDirection = 'asc' AND @OrderBy = 'City' THEN City END ASC
  32. ,CASE WHEN @SortDirection = 'desc' AND @OrderBy = 'City' THEN City END DESC
  33. ,CASE WHEN @SortDirection = 'asc' AND @OrderBy = 'Region' THEN Region END ASC
  34. ,CASE WHEN @SortDirection = 'desc' AND @OrderBy = 'Region' THEN Region END DESC
  35. ,CASE WHEN @SortDirection = 'asc' AND @OrderBy = 'PostalCode' THEN PostalCode END ASC
  36. ,CASE WHEN @SortDirection = 'desc' AND @OrderBy = 'PostalCode' THEN PostalCode END DESC
  37. ,CASE WHEN @SortDirection = 'asc' AND @OrderBy = 'Country' THEN Country END ASC
  38. ,CASE WHEN @SortDirection = 'desc' AND @OrderBy = 'Country' THEN Country END DESC
  39. OFFSET ((@PageNumber-1) * @PageSize) ROWS
  40. FETCH NEXT @PageSize ROWS ONLY
Here, you have 2 ways to add Web API class. You can add new Web API controller and select model class and data source that will generate API class with entity framework. Another way is to generate it manually. So in this article, I will create a manual API class.
  1. public partial class GetEmployeeWithPaging_Result {
  2. public int EmployeeID {
  3. get;
  4. set;
  5. }
  6. public string FirstName {
  7. get;
  8. set;
  9. }
  10. public string LastName {
  11. get;
  12. set;
  13. }
  14. public string City {
  15. get;
  16. set;
  17. }
  18. public string Region {
  19. get;
  20. set;
  21. }
  22. public string PostalCode {
  23. get;
  24. set;
  25. }
  26. public string Country {
  27. get;
  28. set;
  29. }
  30. public string Notes {
  31. get;
  32. set;
  33. }
  34. public Nullable < int > TotalCount {
  35. get;
  36. set;
  37. }
  38. }
Now, add a builder class.

  1. /// <summary>
  2. ///
  3. /// </summary>
  4. /// <param name="PageNumber"></param>
  5. /// <param name="PageSize"></param>
  6. /// <param name="OrderBy"></param>
  7. /// <param name="SortDirection"></param>
  8. /// <returns></returns>
  9. public async Task < List < GetEmployeeWithPaging_Result >> GetEmployeeWithPaging(int PageNumber, int PageSize, string OrderBy, string SortDirection) {
  10. try {
  11. // Create the SQL param with the id provided by the caller
  12. var pageNumber = new SqlParameter("PageNumber", PageNumber == 0 ? (object) DBNull.Value : PageNumber);
  13. var pageSize = new SqlParameter("PageSize", PageSize == 0 ? (object) DBNull.Value : PageSize);
  14. var orderBy = new SqlParameter("OrderBy", OrderBy == null ? (object) DBNull.Value : OrderBy);
  15. var sortDirection = new SqlParameter("SortDirection", SortDirection == null ? (object) DBNull.Value : SortDirection);
  16. // Create an enumerated list of SearchProgramOptions objects
  17. var result = await db.Database.SqlQuery < GetEmployeeWithPaging_Result > ("GetEmployeeWithPaging @PageNumber,@PageSize,@OrderBy,@SortDirection", pageNumber, pageSize, orderBy, sortDirection).ToListAsync();
  18. return result;
  19. } catch (Exception ex) {
  20. // Something didn't go as expected - this Exception handler should be more verbose
  21. throw ex;
  22. }
  23. }

If you want to use a stored procedure, then read my previous article.

Web API

Right click on controller folder, click Add and select Controller and select Web API 2 Controller – Empty.

  1. [Route("GetEmployeeWithPaging")]
  2. public async Task < IEnumerable < GetEmployeeWithPaging_Result >> GetEmployeeWithPaging(int PageNumber = 0, int PageSize = 0, string OrderBy = null, string SortDirection = null)
  3. {
  4. return await _employeeVMBuilder.GetEmployeeWithPaging(PageNumber, PageSize, OrderBy, SortDirection);
  5. }
Thus, we are done with Entity framework and API Controller here. Now, install the files given below, using "Manage NuGet Package".


Add JavaScript files and CSS reference in BundleConfig.cs.

  1. bundles.Add(new ScriptBundle("~/bundles/angular").Include(
  2. "~/Scripts/angular.js",
  3. "~/Scripts/angular-route.js",
  4. "~/Scripts/ui-grid.js",
  5. "~/Scripts/angular-ui/ui-bootstrap.js",
  6. "~/Scripts/angular-ui/ui-bootstrap-tpls.js"));
  7. bundles.Add(new ScriptBundle("~/bundles/employee").Include(
  8. "~/Angular/app.js",
  9. "~/Angular/Services/employeeService.js",
  10. "~/Angular/Controller/employeeController.js",
  11. "~/Angular/Controller/editEmployeeController.js",
  12. "~/Angular/Controller/addEmployeeController.js"));

And, render on _layout.cshtml.

  1. @Scripts.Render("~/bundles/jquery")
  2. @Scripts.Render("~/bundles/bootstrap")
  3. @Scripts.Render("~/bundles/angular")
  4. @Scripts.Render("~/bundles/employee")
  5. @RenderSection("scripts", required: false)

Now, add a new Angular Controller with scope. I am using just one script for Module, Service, and Controller. You can have it separate if working on a big project.

Module

  1. //Define an angular module for our app
  2. var app = angular.module('app', ['ngRoute', 'ui.grid', 'ui.grid.edit', 'ui.grid.pagination', 'ui.grid.autoResize', 'ui.grid.expandable', 'ui.grid.selection', 'ui.grid.pinning', 'ui.bootstrap']).config(function($routeProvider, $locationProvider) {
  3. $locationProvider.hashPrefix('');
  4. $routeProvider.when('/', {
  5. templateUrl: 'Home',
  6. controller: 'homeController'
  7. }).when('/employee', {
  8. templateUrl: 'Employee',
  9. controller: 'employeeController'
  10. });
  11. //$locationProvider.html5Mode(true);
  12. //$locationProvider.html5Mode(true).hashPrefix('*');
  13. });

Service

  1. //get employees with paging params
  2. this.getEmployeeWithPaging = function (PageNumber,PageSize,OrderBy,SortDirection) {
  3. var req = $http.get('api/EmployeeAPI/GetEmployeeWithPaging', { params: { PageNumber:PageNumber,
  4. PageSize:PageSize,
  5. OrderBy:OrderBy,
  6. SortDirection:SortDirection } });
  7. return req;
  8. };

Controller

  1. app.controller("employeeController", function($scope, $filter, employeeService, $window, $http, $log, $interval, $uibModal) {
  2. init();
  3. function init() {
  4. //Pagination varibles
  5. var paginationOptions = {
  6. pageNumber: 1,
  7. pageSize: 10,
  8. sort: {
  9. columnName: 'EmployeeID',
  10. isAscending: false,
  11. }
  12. };
  13. $scope.currentPage = 1;
  14. $scope.pageSize = paginationOptions.pageSize;
  15. //end here
  16. $scope.loadData = function() {
  17. employeeService.getEmployeeWithPaging(paginationOptions.pageNumber, paginationOptions.pageSize, null, paginationOptions.sort).then(function(result) {
  18. $scope.gridOptions.totalItems = result.data[0].TotalCount;
  19. $scope.totalPage = Math.ceil($scope.gridOptions.totalItems / $scope.pageSize);
  20. $scope.gridOptions.data = result.data;
  21. console.log($scope.Employees);
  22. }, function(error) {
  23. $window.alert('Oops! Something went wrong while fetching employee data.');
  24. });
  25. };
  26. $scope.loadData();
  27. $scope.gridOptions = {
  28. enableRowSelection: true,
  29. selectionRowHeaderWidth: 35,
  30. enableRowHeaderSelection: false,
  31. //Added for custom paging
  32. paginationPageSizes: [$scope.pageSize, $scope.pageSize * 2, $scope.pageSize * 3],
  33. paginationPageSize: paginationOptions.pageSize,
  34. useExternalPagination: true, // custom
  35. useExternalSorting: true, // custom
  36. useExternalFiltering: true, // custom
  37. enableSorting: true,
  38. columnDefs: [{
  39. name: 'Edit',
  40. field: 'EmployeeID',
  41. width: '10%',
  42. enableColumnMenu: false,
  43. cellTemplate: '<button title="Edit" class="btn btn-xs btn-primary fa fa-edit" ng-click="grid.appScope.editEmployee(row)">Edit </button>',
  44. width: 50,
  45. pinnedLeft: false,
  46. enableHiding: false,
  47. exporterSuppressExport: true,
  48. enableSorting: false,
  49. enableFiltering: false
  50. }, {
  51. name: 'First Name',
  52. field: 'FirstName',
  53. headerCellClass: 'tablesorter-header-inner',
  54. enableFiltering: true,
  55. enableCellEdit: true,
  56. }, {
  57. name: 'Last Name',
  58. field: 'LastName',
  59. headerCellClass: 'tablesorter-header-inner',
  60. enableFiltering: true,
  61. enableCellEdit: true,
  62. }, {
  63. name: 'City',
  64. field: 'City',
  65. headerCellClass: 'tablesorter-header-inner',
  66. enableFiltering: true,
  67. enableCellEdit: true,
  68. }, {
  69. name: 'Region',
  70. field: 'Region',
  71. enableCellEdit: false,
  72. headerCellClass: 'tablesorter-header-inner',
  73. enableFiltering: true
  74. }, {
  75. name: 'Postal Code',
  76. field: 'PostalCode',
  77. enableCellEdit: false,
  78. headerCellClass: 'tablesorter-header-inner',
  79. enableFiltering: true
  80. }, {
  81. name: 'Country',
  82. field: 'Country',
  83. enableCellEdit: false,
  84. headerCellClass: 'tablesorter-header-inner',
  85. enableFiltering: true
  86. }, {
  87. name: 'Notes',
  88. field: 'Notes',
  89. width: '20%',
  90. enableCellEdit: false,
  91. headerCellClass: 'tablesorter-header-inner',
  92. enableFiltering: true
  93. }],
  94. //This code used for export grid data in csv file
  95. enableGridMenu: true,
  96. enableSelectAll: true,
  97. exporterMenuPdf: false,
  98. enableFiltering: true,
  99. exporterCsvFilename: 'EmployeeList_' + $filter('date')(new Date(), 'MM/dd/yyyy') + '.csv',
  100. exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
  101. onRegisterApi: function(gridApi) {
  102. $scope.gridApi = gridApi;
  103. gridApi.selection.on.rowSelectionChanged($scope, function(row) {
  104. var msg = 'row selected ' + row.isSelected;
  105. $log.log(msg);
  106. console.log(msg);
  107. //$window.alert(msg);
  108. });
  109. gridApi.selection.on.rowSelectionChangedBatch($scope, function(rows) {
  110. var msg = 'rows changed ' + rows.length;
  111. $log.log(msg);
  112. // $window.alert(msg);
  113. console.log(msg);
  114. });
  115. //Added for custom paging
  116. gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
  117. paginationOptions.pageNumber = newPage;
  118. paginationOptions.pageSize = pageSize;
  119. $scope.pageSize = pageSize;
  120. $scope.currentPage = newPage;
  121. $scope.totalPage = Math.ceil($scope.gridOptions.totalItems / $scope.pageSize);
  122. $scope.loadData();
  123. });
  124. //custom sort
  125. $scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
  126. if (sortColumns.length == 0) {
  127. paginationOptions.sort = null;
  128. } else {
  129. paginationOptions.sort = sortColumns[0].sort.direction;
  130. }
  131. $scope.loadData();
  132. });
  133. },
  134. //end here
  135. //data for grid
  136. // data: 'employees'
  137. };
  138. }
  139. //Delete employee
  140. $scope.deleteSelected = function() {
  141. angular.forEach($scope.gridApi.selection.getSelectedRows(), function(data, index) {
  142. $scope.employees.splice($scope.employees.lastIndexOf(data), 1);
  143. });
  144. }*/
  145. //This function is used to open update request popup window
  146. $scope.addEmployee = function() {
  147. var modalInstance = $uibModal.open({
  148. //animation: $ctrl.animationsEnabled,
  149. templateUrl: 'Template/add.html',
  150. controller: 'addEmployeeController', // a controller for modal instance
  151. //controllerUrl: 'controller/test-controller', // can specify controller url path
  152. //controllerAs: 'ctrl', // controller as syntax
  153. //scope: $scope,
  154. size: 'md', // model size
  155. backdrop: 'static',
  156. keyboard: false, // ESC key close enable/disable
  157. //appendTo: parentElem,
  158. resolve: {
  159. //grid: function () { return grid; },
  160. //refreshGrid: function () { return $scope.RefreshGrid.bind(controller, $scope.searchData); },
  161. //row: function () { return row.entity; }
  162. row: function() {
  163. return null;
  164. }
  165. } // data passed to the controller
  166. }).closed.then(function() {
  167. $scope.RefreshGridData();
  168. $scope.showGrid = true;
  169. }, function() {});
  170. };
  171. //Open edit dialog
  172. $scope.editEmployee = function(row) {
  173. var modalInstance = $uibModal.open({
  174. //animation: $ctrl.animationsEnabled,
  175. templateUrl: 'Template/edit.html',
  176. controller: 'editEmployeeController', // a controller for modal instance
  177. //controllerUrl: 'controller/test-controller', // can specify controller url path
  178. //controllerAs: 'ctrl', // controller as syntax
  179. //scope: $scope,
  180. size: 'md', // model size
  181. backdrop: 'static',
  182. keyboard: false, // ESC key close enable/disable
  183. //appendTo: parentElem,
  184. resolve: {
  185. //grid: function () { return grid; },
  186. //refreshGrid: function () { return $scope.RefreshGrid.bind(controller, $scope.searchData); },
  187. row: function() {
  188. return row.entity;
  189. }
  190. } // data passed to the controller
  191. }).closed.then(function() {
  192. $scope.RefreshGridData();
  193. $scope.showGrid = true;
  194. }, function() {});
  195. }
  196. //refresh grid data after save of update
  197. $scope.RefreshGridData = function() {
  198. /* employeeService.getEmployees().then(function (result) {
  199. $scope.gridOptions.data = result.data;
  200. console.log($scope.Employees);
  201. }, function (error) {
  202. $window.alert('Oops! Something went wrong while fetching employee data.');
  203. }); */
  204. $scope.loadData();
  205. }
  206. //end
  207. });

Index

  1. @{
  2. ViewBag.Title = "Index";
  3. Layout = "~/Views/Shared/_Layout.cshtml";
  4. }
  5. <h2>Employee</h2>
  6. <div ng-controller="employeeController">
  7. <div style="padding-left: 30px;">
  8. <button type="button" id="addRow" class="btn btn-success" ng-click="addEmployee()">Add New Employee</button>
  9. </div>
  10. <br />
  11. <div ui-grid="gridOptions"
  12. ui-grid-pagination
  13. ui-grid-selection
  14. ui-grid-exporter
  15. ui-grid-resize-columns
  16. ui-grid-auto-resize
  17. class="grid">
  18. </div>
  19. </div>
As everything is done, run the application.


In the given screenshot, you can see the page index and page size. Click "Next" to see the next page index. Best way to check page index debug your application in debug mode. Every time when you press next you pass updated page index and page size and sorting order. The biggest benefit of server-side custom paging is when you have millions of records and loading is slow then go with custom paging, after custom paging no matter how big database is, you will get result fast because you are fetching 10 records each time.

Conclusion

In this article, we have seen how to implement server-side custom paging with Angular UI-Grid with Web API and Entity Framework in MVC. If you have any questions or comments, drop me a line in the comments section.

In the given screenshot, you can see the page index and page size. Click "Next" to see the next page index. Best way to check page index debug your application in debug mode. Every time when you press next you pass updated page index and page size and sorting order. The biggest benefit of server-side custom paging is when you have millions of records and loading is slow then go with custom paging, after custom paging no matter how big database is, you will get result fast because you are fetching 10 records each time.

Conclusion

In this article, we have seen how to implement server-side custom paging with Angular UI-Grid with Web API and Entity Framework in MVC. If you have any questions or comments, drop me a line in the comments section.

Become a master of the Rubik's Cube with this tutorial. Learn how to solve the cube with the beginner's method!