Saturday, August 10, 2019

Part 7 - How to retrieve and display data With Paging in the ASP.NET Web API using Jquery

Step 1: Add a new Folder (here "ViewModels")

Right click on project name (here "Entities") > Add > new folder

Step 2: Add a new class into that folder (here "EmployeeDataWithPaging")

Right Click on that folder > add > new class > Enter Name > Add.
  1. public class EmployeeDataWithPaging
  2. {
  3. public List<Employee> Employees { get; set; }
  4. public int TotalPage { get; set; }
  5. }

Steps for Web API Application(Service)

Here in this example, the Web API application (service) is "WebApiExample".

Step 3: Add a new Controller in the WEB Api application (here "ExamplePagingController")

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Step 4: Add a new Action (Get) for fetch data from database

  1. public HttpResponseMessage Get(int pageNo = 1)
  2. {
  3. HttpResponseMessage response = null;
  4. int totalPage, totalRecord, pageSize;
  5. pageSize = 5;
  6. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  7. {
  8. totalRecord = dc.Employees.Count();
  9. totalPage = (totalRecord / pageSize) + ((totalRecord % pageSize) > 0 ? 1 : 0);
  10. var record = (from a in dc.Employees
  11. orderby a.FirstName, a.LastName
  12. select a).Skip((pageNo - 1) * pageSize).Take(pageSize).ToList();
  13. EmployeeDataWithPaging empData = new EmployeeDataWithPaging
  14. {
  15. Employees = record,
  16. TotalPage = totalPage
  17. };
  18. response = Request.CreateResponse(HttpStatusCode.OK, empData);
  19. }
  20. return response;
  21. }

Steps for Web Application (Client Application)

Here in this example, the client application is "WebApiClient.Web".

Step 5: Add a new Action into home controller for get view for show data.

  1. public ActionResult Part7()
  2. {
  3. return View();
  4. }

Step 6 : Add view for that Action, where we will write jquery code for fetch and display data with paging option from web api

Right Click on Action Method (here right click on form action) > Add View... > Enter Name > Add.
View 
  1. @{
  2. ViewBag.Title = "Part7";
  3. }
  4.  
  5. <h2>Part7 - Fetch data from WEB Api and Display data with paging using jquery</h2>
  6. <div id="updatePanel">
  7.  
  8. </div>

Step 7: Write below jquery code for fetch data from web api and show with pagination

  1. <script>
  2. $(document).ready(function () {
  3. var currentPage = 1;
  4. //Load data for page 1 first time
  5. fetchData(1);
  6. // Paging
  7. $('#updatePanel').on('click', '.footerContent a', function (e) {
  8. e.preventDefault();
  9. var pageNo = parseInt($(this).html());
  10. currentPage = pageNo;
  11. fetchData(currentPage);
  12. });
  13.  
  14. //Fetch Data
  15. function fetchData(pageNo) {
  16. //Create loading panel
  17. var $loading = "<div class='loading'>Please wait...</div>";
  18. $('#updatePanel').prepend($loading);
  19. //Ajax call for fetch data from WEB Api
  20. $.ajax({
  21. url: 'http://localhost:1963/api/ExamplePaging',
  22. type: 'GET',
  23. data: { pageNo: pageNo },
  24. dataType: 'json',
  25. success: function (data) {
  26. // generate html and Load data
  27. var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');
  28. var $header = $('<thead/>').html('<tr><th>Name</th><th>Email</th><th>City</th><th>Country</th></tr>');
  29. $table.append($header);
  30.  
  31. //table body
  32. $.each(data.Employees, function (i, emp) {
  33. var $row = $('<tr/>');
  34. $row.append($('<td/>').html(emp.FirstName + ' ' + emp.LastName));
  35. $row.append($('<td/>').html(emp.EmailID));
  36. $row.append($('<td/>').html(emp.City));
  37. $row.append($('<td/>').html(emp.Country));
  38. $table.append($row);
  39. });
  40.  
  41. //table footer (for paging content)
  42. var totalPage = parseInt(data.TotalPage);
  43. var $footer = $('<tr/>');
  44. var $footerTD = $('<td/>').attr('colspan', 4).addClass('footerContent');
  45.  
  46. if (totalPage > 0) {
  47. for (var i = 1; i <= totalPage; i++) {
  48. var $page = $('<span/>').addClass((i == currentPage) ? "current" : "");
  49. $page.html((i == currentPage) ? i : "<a href='#'>" + i + "</a>");
  50. $footerTD.append($page);
  51. }
  52. $footer.append($footerTD);
  53. }
  54. $table.append($footer);
  55.  
  56. $('#updatePanel').html($table);
  57. },
  58. error: function () {
  59. alert('Error! Please try again.');
  60. }
  61. }).done(function () {
  62. //remove loading panel after ajax call complete
  63. $loading.remove();
  64. });
  65. }
  66. });
  67. </script>
Complete View 
  1. @{
  2. ViewBag.Title = "Part7";
  3. }
  4.  
  5. <h2>Part7 - Fetch data from WEB Api and Display data with paging using jquery</h2>
  6. <div id="updatePanel">
  7.  
  8. </div>
  9.  
  10. @section Scripts{
  11. <script>
  12. $(document).ready(function () {
  13. var currentPage = 1;
  14. //Load data for page 1 first time
  15. fetchData(1);
  16. // Paging
  17. $('#updatePanel').on('click', '.footerContent a', function (e) {
  18. e.preventDefault();
  19. var pageNo = parseInt($(this).html());
  20. currentPage = pageNo;
  21. fetchData(currentPage);
  22. });
  23.  
  24. //Fetch Data
  25. function fetchData(pageNo) {
  26. //Create loading panel
  27. var $loading = "<div class='loading'>Please wait...</div>";
  28. $('#updatePanel').prepend($loading);
  29. //Ajax call for fetch data from WEB Api
  30. $.ajax({
  31. url: 'http://localhost:1963/api/ExamplePaging',
  32. type: 'GET',
  33. data: { pageNo: pageNo },
  34. dataType: 'json',
  35. success: function (data) {
  36. // generate html and Load data
  37. var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');
  38. var $header = $('<thead/>').html('<tr><th>Name</th><th>Email</th><th>City</th><th>Country</th></tr>');
  39. $table.append($header);
  40.  
  41. //table body
  42. $.each(data.Employees, function (i, emp) {
  43. var $row = $('<tr/>');
  44. $row.append($('<td/>').html(emp.FirstName + ' ' + emp.LastName));
  45. $row.append($('<td/>').html(emp.EmailID));
  46. $row.append($('<td/>').html(emp.City));
  47. $row.append($('<td/>').html(emp.Country));
  48. $table.append($row);
  49. });
  50.  
  51. //table footer (for paging content)
  52. var totalPage = parseInt(data.TotalPage);
  53. var $footer = $('<tr/>');
  54. var $footerTD = $('<td/>').attr('colspan', 4).addClass('footerContent');
  55.  
  56. if (totalPage > 0) {
  57. for (var i = 1; i <= totalPage; i++) {
  58. var $page = $('<span/>').addClass((i == currentPage) ? "current" : "");
  59. $page.html((i == currentPage) ? i : "<a href='#'>" + i + "</a>");
  60. $footerTD.append($page);
  61. }
  62. $footer.append($footerTD);
  63. }
  64. $table.append($footer);
  65.  
  66. $('#updatePanel').html($table);
  67. },
  68. error: function () {
  69. alert('Error! Please try again.');
  70. }
  71. }).done(function () {
  72. //remove loading panel after ajax call complete
  73. $loading.remove();
  74. });
  75. }
  76. });
  77. </script>
  78. }
  79.  
  80. <style>
  81. /*Add some css for looks good*/
  82. #updatePanel {
  83. width:95%;
  84. margin:0 auto;
  85. position: relative;
  86. }
  87. .loading {
  88. float: left;
  89. position: absolute;
  90. margin-left: 40%;
  91. width: 200px;
  92. top: 100px;
  93. padding: 3px;
  94. border: 1px solid rgb(253, 0, 0);
  95. background-color: rgb(245, 245, 78);
  96. text-align: center;
  97. }
  98. span.current {
  99. cursor: auto !important;
  100. background-color: #6E6E6E !important;
  101. color: #ffffff;
  102. font-weight: bold;
  103. padding: 5px 10px;
  104. border: 1px solid #000000;
  105. margin-right: 4px;
  106. }
  107. td.footerContent span a{
  108. display: inline-block;
  109. padding: 3px 10px;
  110. background-color: #f3f3f3;
  111. margin-right: 4px;
  112. border: 1px solid #998787;
  113. cursor: pointer;
  114. }
  115. td.footerContent span a {
  116. text-decoration:none;
  117. }
  118. td.footerContent{
  119.  
  120. text-align:right;
  121. }
  122. </style>
  123.  

Step-8: Run Application.

Here we need to start both application as the client application will consume services from web api application.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...