ASP.NET Web API Using MVC And jQuery For Paging - Part Nine

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.   
  7. namespace Entities.ViewModels  
  8. {  
  9.     public class EmployeeDataWithPaging  
  10.     {  
  11.         public List<Employee> Employees { getset; }  
  12.         public int TotalPage { getset; }  
  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.   
  10. namespace SatyaWebApi.Controllers  
  11. {  
  12.     public class ExamplePagingController : ApiController  
  13.     {  
  14.         public HttpResponseMessage Get(int pageNo = 1)  
  15.         {  
  16.             HttpResponseMessage response = null;  
  17.             int totalPage, totalRecord, pageSize;  
  18.             pageSize = 5;  
  19.             using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())  
  20.             {  
  21.                 totalRecord = dc.Employees.Count();  
  22.                 totalPage = (totalRecord / pageSize) + ((totalRecord % pageSize) > 0 ? 1 : 0);  
  23.                 var record = (from a in dc.Employees  
  24.                               orderby a.FirstName, a.LastName  
  25.                               select a).Skip((pageNo - 1) * pageSize).Take(pageSize).ToList();  
  26.                 EmployeeDataWithPaging empData = new EmployeeDataWithPaging  
  27.                 {  
  28.                     Employees = record,  
  29.                     TotalPage = totalPage  
  30.                 };  
  31.                 response = Request.CreateResponse(HttpStatusCode.OK, empData);  
  32.             }  
  33.             return response;  
  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.   
  5. <h2>Satyaprakash 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.             fetchData(1);  
  15.             $('#updatePanel').on('click''.footerContent a'function (e) {  
  16.                 e.preventDefault();  
  17.                 var pageNo = parseInt($(this).html());  
  18.                 currentPage = pageNo;  
  19.                 fetchData(currentPage);  
  20.             });  
  21.             function fetchData(pageNo) {       
  22.                 var $loading = "<div class='loading'>Please wait...</div>";  
  23.                 $('#updatePanel').prepend($loading);  
  24.                 $.ajax({  
  25.                     url: 'http://localhost:47250/api/ExamplePaging',  
  26.                     type: 'GET',  
  27.                     data: { pageNo: pageNo },  
  28.                     dataType: 'json',  
  29.                     success: function (data) {  
  30.                         var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');  
  31.                         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>');  
  32.                         $table.append($header);  
  33.                         $.each(data.Employees, function (i, emp) {  
  34.                             var $row = $('<tr/>');  
  35.                             $row.append($('<td/>').html(emp.FirstName + ' ' + emp.LastName));  
  36.                             $row.append($('<td/>').html(emp.EmailID));  
  37.                             $row.append($('<td/>').html(emp.City));  
  38.                             $row.append($('<td/>').html(emp.Country));  
  39.                             $table.append($row);  
  40.                         });  

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

  61.                     $loading.remove();  
  62.                 });  
  63.             }  
  64.         });  
  65.     </script>  
  66. }  
  67.   
  68. <style>

  69.     #updatePanel {  
  70.         width: 95%;  
  71.         margin: 0 auto;  
  72.         position: relative;  
  73.     }  
  74.   
  75.     .loading {  
  76.         float: left;  
  77.         position: absolute;  
  78.         margin-left: 40%;  
  79.         width: 200px;  
  80.         top: 100px;  
  81.         padding: 3px;  
  82.         border: 1px solid rgb(253, 0, 0);  
  83.         background-color: rgb(245, 245, 78);  
  84.         text-align: center;  
  85.     }  
  86.   
  87.     table {  
  88.         font-family: arial, sans-serif;  
  89.         border-collapse: collapse;  
  90.         width: 100%;  
  91.     }  
  92.   
  93.     td, th {  
  94.         border: 1px solid #dddddd;  
  95.         text-align: left;  
  96.         padding: 8px;  
  97.     }  
  98.   
  99.     tr:nth-child(even) {  
  100.         background-color: #dddddd;  
  101.     }  
  102.   
  103.     span.current {  
  104.         cursor: auto !important;  
  105.         background-color: #6E6E6E !important;  
  106.         color: #ffffff;  
  107.         font-weight: bold;  
  108.         padding: 5px 10px;  
  109.         border: 1px solid #000000;  
  110.         margin-right: 4px;  
  111.     }  
  112.   
  113.     td.footerContent span a {  
  114.         display: inline-block;  
  115.         padding: 3px 10px;  
  116.         background-color:chartreuse;  
  117.         margin-right: 4px;  
  118.         border: 1px solid #998787;  
  119.         cursor: pointer;  
  120.     }  
  121.   
  122.     td.footerContent span a {  
  123.         text-decoration: none;  
  124.     }  
  125.   
  126.     td.footerContent {  
  127.         text-align: right;  
  128.     }  
  129. </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) {  

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.     
  5.                         if (totalPage > 0) {    
  6.                             for (var i = 1; i <= totalPage; i++) {    
  7.                                 var $page = $('<span/>').addClass((i == currentPage) ? "current" : "");    
  8.                                 $page.html((i == currentPage) ? i : "<a href='#'>" + i + "</a>");    
  9.                                 $footerTD.append($page);    
  10.                             }    
  11.                             $footer.append($footerTD);    
  12.                         }    
  13.                         $table.append($footer);    
  14.     
  15.                         $('#updatePanel').html($table);    
  16.                     },   
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.         width95%;    
  4.         margin0 auto;    
  5.         positionrelative;    
  6.     }    
  7.     
  8.     .loading {    
  9.         floatleft;    
  10.         positionabsolute;    
  11.         margin-left40%;    
  12.         width200px;    
  13.         top: 100px;    
  14.         padding3px;    
  15.         border1px solid rgb(25300);    
  16.         background-colorrgb(24524578);    
  17.         text-aligncenter;    
  18.     }    
  19.     
  20.     table {    
  21.         font-familyarialsans-serif;    
  22.         border-collapsecollapse;    
  23.         width100%;    
  24.     }    
  25.     
  26.     td, th {    
  27.         border1px solid #dddddd;    
  28.         text-alignleft;    
  29.         padding8px;    
  30.     }    
  31.     
  32.     tr:nth-child(even) {    
  33.         background-color#dddddd;    
  34.     }    
  35.     
  36.     span.current {    
  37.         cursorauto !important;    
  38.         background-color#6E6E6E !important;    
  39.         color#ffffff;    
  40.         font-weightbold;    
  41.         padding5px 10px;    
  42.         border1px solid #000000;    
  43.         margin-right4px;    
  44.     }    
  45.     
  46.     td.footerContent span a {    
  47.         display: inline-block;    
  48.         padding3px 10px;    
  49.         background-color:chartreuse;    
  50.         margin-right4px;    
  51.         border1px solid #998787;    
  52.         cursorpointer;    
  53.     }    
  54.     
  55.     td.footerContent span a {    
  56.         text-decorationnone;    
  57.     }    
  58.     
  59.     td.footerContent {    
  60.         text-alignright;    
  61.     }    
  62. </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
  • Paging using AP.NET Web API.
  • Paging with  loading panel.