Introduction
Web API is the best fit to create a resource-oriented service using HTTP/Restful and it works well with MVC-based applications. For more details, visit this link.
Description
In this session, I will show you the steps to display data with Paging. This steps can be implemented using AP.NET Web API.
Before going through this session, visit my previous sessions,
Steps to be followed.
Step 1
Right click on project name (here "Entities") > Add > New folder.
Step 2
Right Click on that folder > add > new class > Enter Name > Add.
Code Ref
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Entities.ViewModels
  7. {
  8. public class EmployeeDataWithPaging
  9. {
  10. public List<Employee> Employees { get; set; }
  11. public int TotalPage { get; set; }
  12. }
  13. }
Code Description
In this class, I have metioned two properties.
  • Employees for fetching data from database in the table.
  • The display of data with paging.
Step 3
Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > select Templete "empty MVC Controller"> Add.
Add a new Action (Get) for fetching data from the database.
Code Ref
  1. using Entities;
  2. using Entities.ViewModels;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Web.Http;
  9. namespace SatyaWebApi.Controllers
  10. {
  11. public class ExamplePagingController : ApiController
  12. {
  13. public HttpResponseMessage Get(int pageNo = 1)
  14. {
  15. HttpResponseMessage response = null;
  16. int totalPage, totalRecord, pageSize;
  17. pageSize = 5;
  18. using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())
  19. {
  20. totalRecord = dc.Employees.Count();
  21. totalPage = (totalRecord / pageSize) + ((totalRecord % pageSize) > 0 ? 1 : 0);
  22. var record = (from a in dc.Employees
  23. orderby a.FirstName, a.LastName
  24. select a).Skip((pageNo - 1) * pageSize).Take(pageSize).ToList();
  25. EmployeeDataWithPaging empData = new EmployeeDataWithPaging
  26. {
  27. Employees = record,
  28. TotalPage = totalPage
  29. };
  30. response = Request.CreateResponse(HttpStatusCode.OK, empData);
  31. }
  32. return response;
  33. }
  34. }
  35. }
Code Description
Here, I have added a new action method to fetch data from the database as well as implement paging.
Here, I declared some variable and mentioned no. of records per page that is 5.
  1. HttpResponseMessage response = null;
  2. int totalPage, totalRecord, pageSize;
  3. pageSize = 5;
Then, fetch records from database using Entity Data Model and calculate total no. of pages based on records per page as mentioned before.
  1. using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())
  2. {
  3. totalRecord = dc.Employees.Count();
  4. totalPage = (totalRecord / pageSize) + ((totalRecord % pageSize) > 0 ? 1 : 0);
  5. var record = (from a in dc.Employees
  6. orderby a.FirstName, a.LastName
  7. select a).Skip((pageNo - 1) * pageSize).Take(pageSize).ToList();
Then, mention the variable data into properties of class EmployeeDataWithPaging for No. of employee records with paging.
  1. EmployeeDataWithPaging empData = new EmployeeDataWithPaging
  2. {
  3. Employees = record,
  4. TotalPage = totalPage
  5. };
Step 4
Add a new Action into the home controller for getting View for show data.
Code Ref
  1. @{
  2. ViewBag.Title = "Satyaprakash-Fetch data from WEB Api and Display data with paging using jquery";
  3. }
  4. <h2>Satyaprakash Fetch data from WEB Api and Display data with paging using jquery</h2>
  5. <div id="updatePanel">
  6. </div>
  7. @section Scripts{
  8. <script>
  9. $(document).ready(function () {
  10. var currentPage = 1;
  11. fetchData(1);
  12. $('#updatePanel').on('click', '.footerContent a', function (e) {
  13. e.preventDefault();
  14. var pageNo = parseInt($(this).html());
  15. currentPage = pageNo;
  16. fetchData(currentPage);
  17. });
  18. function fetchData(pageNo) {
  19. var $loading = "<div class='loading'>Please wait...</div>";
  20. $('#updatePanel').prepend($loading);
  21. $.ajax({
  22. url: 'http://localhost:47250/api/ExamplePaging',
  23. type: 'GET',
  24. data: { pageNo: pageNo },
  25. dataType: 'json',
  26. success: function (data) {
  27. var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');
  28. var $header = $('<thead/>').html('<tr><th style="background-color: Yellow;color: blue">Name</th><th style="background-color: Yellow;color: blue">Email</th><th style="background-color: Yellow;color: blue">City</th><th style="background-color: Yellow;color: blue">Country</th></tr>');
  29. $table.append($header);
  30. $.each(data.Employees, function (i, emp) {
  31. var $row = $('<tr/>');
  32. $row.append($('<td/>').html(emp.FirstName + ' ' + emp.LastName));
  33. $row.append($('<td/>').html(emp.EmailID));
  34. $row.append($('<td/>').html(emp.City));
  35. $row.append($('<td/>').html(emp.Country));
  36. $table.append($row);
  37. });

  38. var totalPage = parseInt(data.TotalPage);
  39. var $footer = $('<tr/>');
  40. var $footerTD = $('<td/>').attr('colspan', 4).addClass('footerContent');
  41. if (totalPage > 0) {
  42. for (var i = 1; i <= totalPage; i++) {
  43. var $page = $('<span/>').addClass((i == currentPage) ? "current" : "");
  44. $page.html((i == currentPage) ? i : "<a href='#'>" + i + "</a>");
  45. $footerTD.append($page);
  46. }
  47. $footer.append($footerTD);
  48. }
  49. $table.append($footer);
  50. $('#updatePanel').html($table);
  51. },
  52. error: function () {
  53. alert('Error! Please try again.');
  54. }
  55. }).done(function () {

  56. $loading.remove();
  57. });
  58. }
  59. });
  60. </script>
  61. }
  62. <style>

  63. #updatePanel {
  64. width: 95%;
  65. margin: 0 auto;
  66. position: relative;
  67. }
  68. .loading {
  69. float: left;
  70. position: absolute;
  71. margin-left: 40%;
  72. width: 200px;
  73. top: 100px;
  74. padding: 3px;
  75. border: 1px solid rgb(253, 0, 0);
  76. background-color: rgb(245, 245, 78);
  77. text-align: center;
  78. }
  79. table {
  80. font-family: arial, sans-serif;
  81. border-collapse: collapse;
  82. width: 100%;
  83. }
  84. td, th {
  85. border: 1px solid #dddddd;
  86. text-align: left;
  87. padding: 8px;
  88. }
  89. tr:nth-child(even) {
  90. background-color: #dddddd;
  91. }
  92. span.current {
  93. cursor: auto !important;
  94. background-color: #6E6E6E !important;
  95. color: #ffffff;
  96. font-weight: bold;
  97. padding: 5px 10px;
  98. border: 1px solid #000000;
  99. margin-right: 4px;
  100. }
  101. td.footerContent span a {
  102. display: inline-block;
  103. padding: 3px 10px;
  104. background-color:chartreuse;
  105. margin-right: 4px;
  106. border: 1px solid #998787;
  107. cursor: pointer;
  108. }
  109. td.footerContent span a {
  110. text-decoration: none;
  111. }
  112. td.footerContent {
  113. text-align: right;
  114. }
  115. </style>
Code Description
Load the data for page 1 the first time using function implementation.
  1. var currentPage = 1;
  2. fetchData(1);
Then, implement Paging using jQuery.
  1. $('#updatePanel').on('click', '.footerContent a', function (e) {
  2. e.preventDefault();
  3. var pageNo = parseInt($(this).html());
  4. currentPage = pageNo;
  5. fetchData(currentPage);
  6. });
Then, create a function for fetching Data.
  1. function fetchData(pageNo) {
  2. }
Then, create a loading panel.
  1. var $loading = "<div class='loading'>Please wait...</div>";
  2. $('#updatePanel').prepend($loading);
AJAX call for fetch data from WEB API.
  1. $.ajax({
  2. url: 'http://localhost:47250/api/ExamplePaging',
  3. type: 'GET',
  4. data: { pageNo: pageNo },
  5. dataType: 'json',
  6. success: function (data) {
Generate HTML and load data in table body.
  1. success: function (data) {
  2. var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');
  3. var $header = $('<thead/>').html('<tr><th style="background-color: Yellow;color: blue">Name</th><th style="background-color: Yellow;color: blue">Email</th><th style="background-color: Yellow;color: blue">City</th><th style="background-color: Yellow;color: blue">Country</th></tr>');
  4. $table.append($header);
  5. $.each(data.Employees, function (i, emp) {
  6. var $row = $('<tr/>');
  7. $row.append($('<td/>').html(emp.FirstName + ' ' + emp.LastName));
  8. $row.append($('<td/>').html(emp.EmailID));
  9. $row.append($('<td/>').html(emp.City));
  10. $row.append($('<td/>').html(emp.Country));
  11. $table.append($row);
  12. });
Table footer (for paging content).
  1. var totalPage = parseInt(data.TotalPage);
  2. var $footer = $('<tr/>');
  3. var $footerTD = $('<td/>').attr('colspan', 4).addClass('footerContent');
  4. if (totalPage > 0) {
  5. for (var i = 1; i <= totalPage; i++) {
  6. var $page = $('<span/>').addClass((i == currentPage) ? "current" : "");
  7. $page.html((i == currentPage) ? i : "<a href='#'>" + i + "</a>");
  8. $footerTD.append($page);
  9. }
  10. $footer.append($footerTD);
  11. }
  12. $table.append($footer);
  13. $('#updatePanel').html($table);
  14. },
Remove loading panel after AJAX call complete.
  1. .done(function () {
  2. $loading.remove();
  3. });
I have added some css fora good table and paging appearance.
  1. <style>
  2. #updatePanel {
  3. width: 95%;
  4. margin: 0 auto;
  5. position: relative;
  6. }
  7. .loading {
  8. float: left;
  9. position: absolute;
  10. margin-left: 40%;
  11. width: 200px;
  12. top: 100px;
  13. padding: 3px;
  14. border: 1px solid rgb(253, 0, 0);
  15. background-color: rgb(245, 245, 78);
  16. text-align: center;
  17. }
  18. table {
  19. font-family: arial, sans-serif;
  20. border-collapse: collapse;
  21. width: 100%;
  22. }
  23. td, th {
  24. border: 1px solid #dddddd;
  25. text-align: left;
  26. padding: 8px;
  27. }
  28. tr:nth-child(even) {
  29. background-color: #dddddd;
  30. }
  31. span.current {
  32. cursor: auto !important;
  33. background-color: #6E6E6E !important;
  34. color: #ffffff;
  35. font-weight: bold;
  36. padding: 5px 10px;
  37. border: 1px solid #000000;
  38. margin-right: 4px;
  39. }
  40. td.footerContent span a {
  41. display: inline-block;
  42. padding: 3px 10px;
  43. background-color:chartreuse;
  44. margin-right: 4px;
  45. border: 1px solid #998787;
  46. cursor: pointer;
  47. }
  48. td.footerContent span a {
  49. text-decoration: none;
  50. }
  51. td.footerContent {
  52. text-align: right;
  53. }
  54. </style>
OUTPUT
The number of records per page. That is 5 and paging feature.
For loading panel.
Added style sheet for a good look in table and paging.
SUMMARY