Bootstrap Pagination for ASP.NET GridView

Bootstrap offers a pagination component that looks simple yet the large block is hard to miss, easily scalable, and provides large click areas. This is a static component and there are few dynamic jQuery plugins available that simplifies the rendering of Bootstrap Pagination. In this post, I am going to use BootPag jQuery plugin and implement server side paging in ASP.Net GridView. 




jQuery Bootpag is an enhanced bootstrap pagination plugin. It is very easy to set up – we only have to pass a callback function and listen for the page event. Inside that function, we can update the GridView with the content by making ajax calls to server side web method.

1. Create an ASP.NET Web Application. Download and required scripts to it,
2. Let us use a csv file with some sample data to populate gridview. I have created a csv file and stored it in Project/App_Data folder. 

We need a model class to represent the columns in the csv file (country, revenue, salemanager, year). I am implementing server side pagination in this example and at any point of time I am returning only 5 records (maximum records per page) from the server. 

Revenue.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;

namespace GridViewBootstrapPagination
{
    public class Revenue
    {

        public Revenue(string country, string revenue, string salesmanager, string year)
        {
            this.country = country;
            this.revenue = revenue;
            this.salesmanager = salesmanager;
            this.year = year;
        }

        public Revenue() { }
         
        public string country { get; set; }
        public string revenue { get; set; }
        public string salesmanager { get; set; }
        public string year { get; set; }

        public List<Revenue> GetRevenueDetails(int pagenumber,int maxrecords)
        {
            List<Revenue> lstRevenue = new List<Revenue>();
            string filename = HttpContext.Current.Server.MapPath("~/App_Data/country_revenue.csv");
            int startrecord = (pagenumber * maxrecords) - maxrecords;
            if (File.Exists(filename))
            {
                IEnumerable<int> range = Enumerable.Range(startrecord, maxrecords);
                IEnumerable<String> lines = getFileLines(filename, range);
                foreach (String line in lines)
                {
                    string[] row = line.Split(',');
                    lstRevenue.Add(new Revenue(row[0], row[1], row[2], row[3]));
                }
                   
            }
            return lstRevenue;
        }

        public static IEnumerable<String> getFileLines(String path, IEnumerable<int> lineIndices)
        {
            return File.ReadLines(path).Where((l, i) => lineIndices.Contains(i));
        }

        public int GetTotalRecordCount()
        {          
            string filename = HttpContext.Current.Server.MapPath("~/App_Data/country_revenue.csv");
            int count = 0;
            if (File.Exists(filename))
            {
                string[] data = File.ReadAllLines(filename);
                count= data.Length;
            }
            return count;
        }        
    }
}

4. Next let us create a web form with a gridview, and use bootpag plugin to generate pagination component for the gridview,

Default.aspx

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Bootstrap Pagination for GridView</title>
    <link href="Styles/bootstrap.min.css" rel="stylesheet" />
    <script src="Scripts/jquery-1.8.2.js"></script>
    <script src="Scripts/jquery.bootpag.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            // init bootpag
            var count = GetTotalPageCount();
            $('#page-selection').bootpag(
                {
                    total:count
                }).on("page", function (event, num) {
                    GetGridData(num);
            });
        });

        function GetGridData(num) {        
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetRevenueDetail",
                data: "{ \"pagenumber\":" + num + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    bindGrid(data.d);
                },
                error: function (xhr, status, err) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);

                }
            });
        }

        function bindGrid(data) {
            $("[id*=gvBSPagination] tr").not(":first").not(":last").remove();
            var table1 = $('[id*=gvBSPagination]');
            var firstRow = "$('[id*=gvBSPagination] tr:first-child')";
            for (var i = 0; i < data.length; i++) {
                var rowNew = $("<tr><td></td><td></td><td></td><td></td></tr>");
                rowNew.children().eq(0).text(data[i].country);
                rowNew.children().eq(1).text(data[i].revenue);
                rowNew.children().eq(2).text(data[i].salesmanager);
                rowNew.children().eq(3).text(data[i].year);
                rowNew.insertBefore($("[id*=gvBSPagination] tr:last-child"));
            }
        }

        function GetTotalPageCount() {
            var mytempvar = 0;
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetTotalPageCount",
                data: "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async:false,
                success: function (data) {
                    mytempvar=data.d;
                    
                },
                error: function (xhr, status, err) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);

                }
            });
            return mytempvar;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="width:670px;margin-left:auto;margin-right:auto;">
        <asp:GridView ID="gvBSPagination" runat="server" CssClass="table table-striped table-bordered table-condensed" Width="660px" AllowPaging="true" PageSize="5" OnPreRender="gvBSPagination_PreRender">
            <PagerTemplate>
                <div id="page-selection" class="pagination-centered"></div>
            </PagerTemplate>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Now let us take a closer look at the jQuery script. Initially when the page loads, an ajax call will be made to server side method called, GetTotalPageCount - this method fetches the total number of records contained in the csv file once when the page initially loads. This is required because we have to pass total record count as input for bootpag plugin to generate list of paging controls based on it(option : total). GridView is loaded with the first five records on page load from the server side and on every click on the pager control, ajax call is made to the server side method called, GetGridData with the current page number as parameter - this method is responsible for fetching records from csv file based on the current page number.

Note that GridView has a pager template in which a div with id "page-selection" is placed. Bootpag plugin generates list of paging controls inside this div on page load.

5. Final step is to load gridview on Page_Load and define server side Web Method to execute jQuery Ajax Calls in the code behind file,

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Services;


namespace GridViewBootstrapPagination
{
    public partial class Default : System.Web.UI.Page
    {
        private const int MAX_RECORDS = 5;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            string filename = Server.MapPath("~/App_Data/country_revenue.csv");
            if (!IsPostBack)
            {
                List<Revenue> revenue = GetRevenueDetail(1);
                gvBSPagination.DataSource = revenue;
                gvBSPagination.DataBind();

            }
           
        }

        [WebMethod]
     [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]        
        public static List<Revenue> GetRevenueDetail(int pagenumber)
           {
               Revenue rv = new Revenue();
               List<Revenue> lstrevenue = rv.GetRevenueDetails(pagenumber,MAX_RECORDS);            
               return lstrevenue;
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static int GetTotalPageCount()
        {
            int count=0;
            Revenue rv=new Revenue();
            count = rv.GetTotalRecordCount();
            count = count / MAX_RECORDS;
            return count;
        }

        protected void gvBSPagination_PreRender(object sender, EventArgs e)
        {
            GridView gv = (GridView)sender;
            GridViewRow pagerRow = (GridViewRow)gv.BottomPagerRow;

            if (pagerRow != null && pagerRow.Visible == false)
                pagerRow.Visible = true;
        }
    }
}

That  is all! Now run the project and view "Default.aspx" in browser to see the gridview working with Bootstrap Pagination component.

1 comment:

Contact Form

Name

Email *

Message *