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



Introduction

In this post, I am going to explain Part 7 - How to retrieve and display data With Paging in the ASP.NET Web API using Jquery

In  previous articles, we have seen How to implement Custom Paging and Sorting in ASP.Net Gridview and How to implement Custom Paging in webgrid in MVC4 application and more about paging on tabular data. Here we will see How to retrieve and display data With Paging in the ASP.NET Web API using Jquery.
This post is 7th part of a series called Getting Started with ASP.NET WEB API
  1. Part1 - How to retrieve data from the database in the ASP.NET Web API using Jquery
  2. Part 2 - How to retrieve data from the database in the ASP.NET Web API using Http Client
  3. Part 3 - How to post data with validation in the ASP.NET Web API using Jquery
  4. Part 4 - How to post data with validation in the ASP.NET Web API using Http Client
  5. Part 5 - How to upload files in the ASP.NET Web API using Jquery
  6. Part 6 - How to upload files in the ASP.NET Web API using Http Client
  7. Part 7 - How to retrieve and display data With Paging in the ASP.NET Web API using Jquery

Steps for "Entities" application

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.
public class EmployeeDataWithPaging
{
    public List<Employee> Employees { get; set; }
    public int TotalPage { get; set; }
}
                    

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

public HttpResponseMessage Get(int pageNo = 1)
{
    HttpResponseMessage response = null;
    int totalPage, totalRecord, pageSize;
    pageSize = 5;
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        totalRecord = dc.Employees.Count();
        totalPage = (totalRecord / pageSize) + ((totalRecord % pageSize) > 0 ? 1 : 0);
        var record = (from a in dc.Employees
                        orderby a.FirstName, a.LastName
                        select a).Skip((pageNo - 1) * pageSize).Take(pageSize).ToList();
        EmployeeDataWithPaging empData = new EmployeeDataWithPaging
        {
                Employees = record,
                TotalPage = totalPage
        };
        response = Request.CreateResponse(HttpStatusCode.OK, empData);
    }
    return response;
}
                    

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.

public ActionResult Part7()
{
    return View();
}
                    

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
@{
    ViewBag.Title = "Part7";
}

<h2>Part7 - Fetch data from WEB Api and Display data with paging using jquery</h2>
<div id="updatePanel">

</div>
                    

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

<script>
    $(document).ready(function () {
        var currentPage = 1;
        //Load data for page 1 first time
        fetchData(1);
        // Paging 
        $('#updatePanel').on('click', '.footerContent a', function (e) {
            e.preventDefault();
            var pageNo = parseInt($(this).html());
            currentPage = pageNo;
            fetchData(currentPage);
        });

        //Fetch Data
        function fetchData(pageNo) {
            //Create loading panel
            var $loading = "<div class='loading'>Please wait...</div>";
            $('#updatePanel').prepend($loading);
            //Ajax call for fetch data from WEB Api
            $.ajax({
                url: 'http://localhost:1963/api/ExamplePaging',
                type: 'GET',
                data: { pageNo: pageNo },
                dataType: 'json',
                success: function (data) {
                    // generate html and Load data 
                    var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');
                    var $header = $('<thead/>').html('<tr><th>Name</th><th>Email</th><th>City</th><th>Country</th></tr>');
                    $table.append($header);

                    //table  body 
                    $.each(data.Employees, function (i, emp) {
                        var $row = $('<tr/>');
                        $row.append($('<td/>').html(emp.FirstName + ' ' + emp.LastName));
                        $row.append($('<td/>').html(emp.EmailID));
                        $row.append($('<td/>').html(emp.City));
                        $row.append($('<td/>').html(emp.Country));
                        $table.append($row);
                    });

                    //table footer (for paging content)
                    var totalPage = parseInt(data.TotalPage);
                    var $footer = $('<tr/>');
                    var $footerTD = $('<td/>').attr('colspan', 4).addClass('footerContent');

                    if (totalPage > 0) {
                        for (var i = 1; i <= totalPage; i++) {
                            var $page = $('<span/>').addClass((i == currentPage) ? "current" : "");
                            $page.html((i == currentPage) ? i : "<a href='#'>" + i + "</a>");
                            $footerTD.append($page);
                        }
                        $footer.append($footerTD);
                    }
                    $table.append($footer);

                    $('#updatePanel').html($table);
                },
                error: function () {
                    alert('Error! Please try again.');
                }
            }).done(function () {
                //remove loading panel after ajax call complete
                $loading.remove();
            });
        }
    });
</script>
                    
Complete View
@{
        ViewBag.Title = "Part7";
    }

    <h2>Part7 - Fetch data from WEB Api and Display data with paging using jquery</h2>
    <div id="updatePanel">

    </div>

@section Scripts{
    <script>
        $(document).ready(function () {
            var currentPage = 1;
            //Load data for page 1 first time
            fetchData(1);
            // Paging 
            $('#updatePanel').on('click', '.footerContent a', function (e) {
                e.preventDefault();
                var pageNo = parseInt($(this).html());
                currentPage = pageNo;
                fetchData(currentPage);
            });

            //Fetch Data
            function fetchData(pageNo) {
                //Create loading panel
                var $loading = "<div class='loading'>Please wait...</div>";
                $('#updatePanel').prepend($loading);
                //Ajax call for fetch data from WEB Api
                $.ajax({
                    url: 'http://localhost:1963/api/ExamplePaging',
                    type: 'GET',
                    data: { pageNo: pageNo },
                    dataType: 'json',
                    success: function (data) {
                        // generate html and Load data 
                        var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');
                        var $header = $('<thead/>').html('<tr><th>Name</th><th>Email</th><th>City</th><th>Country</th></tr>');
                        $table.append($header);

                        //table  body 
                        $.each(data.Employees, function (i, emp) {
                            var $row = $('<tr/>');
                            $row.append($('<td/>').html(emp.FirstName + ' ' + emp.LastName));
                            $row.append($('<td/>').html(emp.EmailID));
                            $row.append($('<td/>').html(emp.City));
                            $row.append($('<td/>').html(emp.Country));
                            $table.append($row);
                        });

                        //table footer (for paging content)
                        var totalPage = parseInt(data.TotalPage);
                        var $footer = $('<tr/>');
                        var $footerTD = $('<td/>').attr('colspan', 4).addClass('footerContent');

                        if (totalPage > 0) {
                            for (var i = 1; i <= totalPage; i++) {
                                var $page = $('<span/>').addClass((i == currentPage) ? "current" : "");
                                $page.html((i == currentPage) ? i : "<a href='#'>" + i + "</a>");
                                $footerTD.append($page);
                            }
                            $footer.append($footerTD);
                        }
                        $table.append($footer);

                        $('#updatePanel').html($table);
                    },
                    error: function () {
                        alert('Error! Please try again.');
                    }
                }).done(function () {
                    //remove loading panel after ajax call complete
                    $loading.remove();
                });
            }
        });
    </script>
}

<style>
/*Add some css for looks good*/
#updatePanel {
        width:95%;
        margin:0 auto;
        position: relative;
    }
    .loading {
      float: left;
      position: absolute;
      margin-left: 40%;
      width: 200px;
      top: 100px;
      padding: 3px;
      border: 1px solid rgb(253, 0, 0);
      background-color: rgb(245, 245, 78);
      text-align: center;
    }
    span.current {
      cursor: auto !important;
      background-color: #6E6E6E !important;
      color: #ffffff;
      font-weight: bold;
      padding: 5px 10px;
      border: 1px solid #000000;
      margin-right: 4px;
    }
    td.footerContent span a{
      display: inline-block;
      padding: 3px 10px;
      background-color: #f3f3f3;
      margin-right: 4px;
      border: 1px solid #998787;
      cursor: pointer;
    }
        td.footerContent span a {
            text-decoration:none;
        }
    td.footerContent{

     text-align:right;
    }
</style>

                  

Step-8: Run Application.

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

Download   Live Demo


retrieve and display data With Paging in the ASP.NET Web API using Jquery

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.