Bootstrap Pagination for ASP.NET GridView

DEMO DOWNLOAD Bootstrap offers a pagination component that looks simple yet the  large block is hard to miss, easily scalable, a...




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.

Update: There is one more easy way of doing this. bs.pagination.js is a jquery script written by Issam Ali and is way more simpler than the approach i explained above. Please have a look at the below links,

https://github.com/issamalidev/bs.pagination.js
http://stackoverflow.com/questions/22420602/simple-script-to-apply-bootstrap-pagination-style-in-asp-net-gridview



Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts.Thanks for reading!! 



Subscribe to GET LATEST ARTICLES!


Related

Jquery 2407883472760280183

Post a Comment

  1. how its work when there is 6 data and i want to show 4 per page??

    ReplyDelete
  2. Hi. Great Tutorial. I have tried to implement it with my own csv file, but my problem is as follows:

    I just addded a extra coulomb, but it doesnt show it on gridview? Is there somewhere I forgot to change?

    ReplyDelete
    Replies
    1. Nevermind, found it :) Great tutorial though!

      Delete
  3. How would I use a SQL datasource with this? What about your example would be different?

    ReplyDelete
  4. good article but can not validate any control on page as Webmethod static method not allowing to access any control of page.

    ReplyDelete
  5. how to use sql server data with your examlpe.. code plz..
    mail id rahul.sharma@programmer.net

    ReplyDelete
  6. Truly, this article is really one of the very best in the history of articles. I am a antique ’Article’ collector and I sometimes read some new articles if I find them interesting. And I found this one pretty fascinating and it should go into my collection. Very good work!
    data science course in India

    ReplyDelete
  7. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
    Artificial Intelligence Course

    ReplyDelete
  8. The blog written is extremely impressive, with a great topic. However, a bit more research could have strengthened it even further. You can explore the services as offered by livewebtutors a premium academic writing services platform offering the best of MLA Referencing Generator teamed with knowledge and experience.

    ReplyDelete
  9. The site loading speed is incredible. It seems that you’re doing any distinctive trick. Furthermore, The contents are masterpiece. you’ve done a magnificent activity on this topic!

    온라인카지노사이트
    안전놀이터
    토토

    ReplyDelete
  10. I like the efforts you have put in this, appreciate it for all the great content.

    사설토토
    바카라사이트
    파워볼사이트

    ReplyDelete
  11. I like what you guys are up also. Such clever work and reporting! Keep up the excellent works guys I’ve incorporated you guys to my blogroll. I think it’ll improve the value of my web site

    토토사이트
    스포츠토토

    ReplyDelete
  12. I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success .. 온라인카지노사이트

    ReplyDelete
  13. Thanks so very much for taking your time to create this very useful and informative site. I have learned a lot from your site. 카지노사이트윈

    ReplyDelete
  14. I got this site from my friend who informed me concerning this site and at the moment this time I am visiting this website and reading very informative articles at this place.
    고군분투 토토사이트

    ReplyDelete
  15. 카지노사이트 Appreciate the recommendation. Will try it out.

    ReplyDelete
  16. 스포츠토토
    토토

    you are in point of fact a excellent webmaster. The website loading pace is amazing.

    ReplyDelete
  17. I surprised with the research you made to create this actual post incredible.
    Fantastic job! 풀싸롱
    That is a really good tip especially to those fresh to the blogosphere.


    ReplyDelete
  18. I do accept as true with all the concepts you’ve offered
    on your post. They are very convincing and can definitely work.
    Nonetheless, the posts are very quick for starters. May just you please lengthen them a bit from next time?
    스포츠토토

    ReplyDelete
  19. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info.
    안전놀이터 모음

    ReplyDelete
  20. I think there are lots of more enjoyable instances ahead for individuals who take a look
    at your blog post.휴게텔
    Yeah bookmaking this wasn't a bad determination outstanding post!


    ReplyDelete
  21. Wow that was odd. I just wrote an really long comment but after I
    clicked submit my comment didn't show up. Grrrr... well I'm
    not writing all that over again. Regardless, just wanted to say excellent blog!
    부산달리기

    ReplyDelete
  22. Good day! I could have sworn I've been to this website
    before but after reading through some of the post I realized it's new
    to me. Nonetheless, I'm definitely glad I found it and I'll be bookmarking and checking
    back frequently!
    Here is my web site 출장안마

    ReplyDelete
  23. It’s hard to come by knowledgeable people for this subject, but you sound like you know what you’re talking about!
    Thanks카지노사이트

    ReplyDelete
  24. I truly appreciate this article.Really looking forward to read more. Great. Satta Matka

    ReplyDelete

  25. 39 years old Video Producer Kristopher from La Prairie, has
    hobbies and interests for example model railways,
    and scrabble. that covered going to Tyre.
    스포츠토토


    ReplyDelete
  26. Hello, I am one of the most impressed people in your article. 안전놀이터추천 I'm very curious about how you write such a good article. Are you an expert on this subject? I think so. Thank you again for allowing me to read these posts, and have a nice day today. Thank you.


    ReplyDelete
  27. Youre so right. Im there with you. Your weblog is definitely worth a read if anyone comes throughout it. Im lucky I did because now Ive received a whole new view of this. 먹튀검증사이트

    ReplyDelete
  28. This article content is really unique and amazing. This article really helpful and explained very well. So I am really thankful to you for sharing keep it up.. Mason

    ReplyDelete
  29. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article :D 먹튀검증

    ReplyDelete
  30. 스포츠토토 Howdy just wanted to give you a quick heads up.
    The text in your post seem to be running off
    the screen in Opera. I’m not sure if this is a format issue or something to do
    with browser compatibility but I thought I’d post
    to let you know. The design look great though! Hope you get the problem
    fixed soon. Cheers

    ReplyDelete
  31. 카지노사이트홈 I think this is among the most significant information for me.
    And i’m glad reading your article. But wanna remark on some general things, The web site
    style is perfect, the articles is really great : D. Good job,
    cheers

    ReplyDelete
  32. It's great. You will certainly really feel that your writing is extraordinary even if you consider it. I enjoyed to see your writing and also my sensations are still sticking around. I wish you will certainly be impressed similar to me when you see my writing. Would certainly you such as ahead as well as see my message? 안전한 바카라사이트

    ReplyDelete
  33. If some one wishes to be updated with most recent technologies afterward
    he must be pay a quick visit this web site and
    be up to date everyday.Click Here 인터넷경마


    2JIYANGWOOK

    ReplyDelete
  34. All your hard work is much appreciated. This content data gives truly quality and unique information. I’m definitely going to look into it. Really very beneficial tips are provided here and, Thank you so much. Keep up the good works.
    카지노사이트

    ReplyDelete
  35. The blog is instructive additionally Wow, great blog article 토토추천

    ReplyDelete
  36. You obviously know what youre talking about 메이저사이트 Thank you for sharing your thoughts. I really appreciate your

    ReplyDelete
  37. We are linking to this great post on our website Thank you for your always good posts 먹튀폴리스

    ReplyDelete
  38. Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this give more information on this topics in your next articles 토토사이트검증

    ReplyDelete
  39. Great information and it is also very well written 안전한놀이터 I will bookmark and comeback really the best on this valuable topic

    ReplyDelete
  40. I like to recommend exclusively fine plus 메이저검증업체 efficient information and facts, hence notice it: coryxkenshin merch

    ReplyDelete
  41. I finally found what I was looking for! I'm so happy. 메이저사이트


    ReplyDelete
  42. Nice to meet you. Your website is full of really interesting topics. It helps me a lot. I have a similar site. We would appreciate it if you visit once and leave your opinion. 안전놀이터추천


    ReplyDelete
  43. From some point on, I am preparing to build my site while browsing various sites. It is now somewhat completed. If you are interested, please come to play with 토토사이트!!


    ReplyDelete
  44. When I read an article on this topic, 카지노사이트검증 the first thought was profound and difficult, and I wondered if others could understand.. My site has a discussion board for articles and photos similar to this topic. Could you please visit me when you have time to discuss this topic?


    ReplyDelete
  45. Hello ! I am the one who writes posts on these topics크레이지슬롯 I would like to write an article based on your article. When can I ask for a review?


    ReplyDelete
  46. I am very impressed with your writing안전놀이터추천 I couldn't think of this, but it's amazing! I wrote several posts similar to this one, but please come and see!


    ReplyDelete
  47. Hello, I am one of the most impressed people in your article. 먹튀검증 What you wrote was very helpful to me. Thank you. Actually, I run a site similar to you. If you have time, could you visit my site? Please leave your comments after reading what I wrote. If you do so, I will actively reflect your opinion. I think it will be a great help to run my site. Have a good day.


    ReplyDelete
  48. Excellent Blog! I would like to thank you for the efforts you have made in writing this post. Gained lots of knowledge.
    Best Refrigerator Repair Service in Hyderabad

    ReplyDelete
  49. It's the same topic , but I was quite surprised to see the opinions I didn't think of. My blog also has articles on these topics, so I look forward to your visit.오공슬롯


    ReplyDelete
  50. What a post I've been looking for! I'm very happy to finally read this post. 메이저사이트추천 Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.


    ReplyDelete
  51. Hello, I am one of the most impressed people in your article. 온라인바카라 If possible, please visit my website as well. Thank you.


    ReplyDelete
  52. I hope you can help me. I've been thinking about this for a long time, but I'm not getting it resolved.온카지노


    ReplyDelete
  53. You are really a genius. I also run a blog, but I don't have genius skills like you. However, I am also writing hard. If possible, please visit my blog and leave a comment. Thank you. 바카라사이트


    ReplyDelete
  54. I figure this article can be enhanced a tad. There are a couple of things that are dangerous here, and if you somehow managed to change these things, this article could wind up a standout amongst your best ones. I have a few thoughts with respect to how you can change these things. 메이저놀이터


    ReplyDelete
  55. Your posts are always informative. This post was a very interesting topic for me too. 파워볼사이트 I wish I could visit the site I run and exchange opinions with each other. So have a nice day.


    ReplyDelete
  56. You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this. 토토사이트

    ReplyDelete
  57. Thanks for the blog filled with so many information. Stopping by your blog helped me to get what I was looking for. Now my task has become as easy as ABC. 안전놀이터


    ReplyDelete
  58. Reseller Hosting in Nepal: Unlocking Opportunities with the Best Web Hosting in Nepalweb hosting services in nepal

    ReplyDelete
  59. Experience the best with Prem Green’s Sojat ki number one mehndi. Renowned for its deep, rich color and exceptional quality, our mehndi is made from 100% natural ingredients. Perfect for all occasions, it ensures beautiful, long-lasting designs that enhance your beauty with a touch of tradition.

    https://www.premgreen.com/sojat-ki-number-one-mehndi/

    ReplyDelete
  60. This master blog on DISC is a treasure trove of information for anyone passionate about understanding and applying DISC principles in their personal and professional life. The structured approach to exploring both foundational concepts and practical applications makes it an indispensable resource for practitioners at all levels. I appreciate the emphasis on bridging theory with real-world scenarios, as it provides actionable insights for fostering communication, productivity, and team cohesion. Strengthscape's commitment to delivering expert advice and evidence-based information shines through, making this blog a must-read for anyone seeking to deepen their expertise or achieve DISC certification. Kudos to the team for creating such a well-rounded and engaging resource! Explore more here: https://strengthscape.com/understanding-disc/

    ReplyDelete

emo-but-icon

SUBSCRIBE


item