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...
https://www.programming-free.com/2013/07/bootstrap-pagination-for-aspnet-gridview.html?m=0
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.
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!!
how its work when there is 6 data and i want to show 4 per page??
ReplyDeleteHi. Great Tutorial. I have tried to implement it with my own csv file, but my problem is as follows:
ReplyDeleteI just addded a extra coulomb, but it doesnt show it on gridview? Is there somewhere I forgot to change?
Nevermind, found it :) Great tutorial though!
DeleteHow would I use a SQL datasource with this? What about your example would be different?
ReplyDeletethanks for great tutorial
ReplyDeletegood article but can not validate any control on page as Webmethod static method not allowing to access any control of page.
ReplyDeletehow to use sql server data with your examlpe.. code plz..
ReplyDeletemail id rahul.sharma@programmer.net
Thanks to the author for sharing this great valuable post with us.
ReplyDeleteIELTS Classes in Mumbai
IELTS Coaching in Mumbai
IELTS Mumbai
IELTS Center in Mumbai
Best IELTS Coaching in Mumbai
Spoken English Classes in Chennai
Spoken English Class in Chennai
Spoken English in Chennai
Thanks for the author for such a valuable post..
ReplyDeleteSAP Training in Chennai
Pearson Vue Exam Center in Chennai
Great Article. Thank you for sharing! Really an awesome post for every one.
ReplyDeleteđại lý vé máy bay đi nhật
giá vé máy bay đi hàn quốc của vietjet
vé máy bay eva đi đài loan>
giá vé máy bay đi bắc kinh trung quốc
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!
ReplyDeletedata science course in India
Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
ReplyDeleteArtificial Intelligence Course
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.
ReplyDeleteMua vé máy bay liên hệ Aivivu, tham khảo
ReplyDeletevé máy bay đi Mỹ giá rẻ 2021
vé máy bay từ mỹ về việt nam mùa dịch
mở chuyến bay từ nhật về việt nam
các đường bay từ canada về việt nam
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온라인카지노사이트
안전놀이터
토토
I like the efforts you have put in this, appreciate it for all the great content.
ReplyDelete사설토토
바카라사이트
파워볼사이트
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토토사이트
스포츠토토
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 .. 온라인카지노사이트
ReplyDeleteThanks so very much for taking your time to create this very useful and informative site. I have learned a lot from your site. 카지노사이트윈
ReplyDeleteI 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고군분투 토토사이트
Yay google is my queen assisted me to find this outstanding website! 온라인카지노
ReplyDelete카지노사이트 Appreciate the recommendation. Will try it out.
ReplyDelete스포츠토토
ReplyDelete토토
you are in point of fact a excellent webmaster. The website loading pace is amazing.
I surprised with the research you made to create this actual post incredible.
ReplyDeleteFantastic job! 풀싸롱
That is a really good tip especially to those fresh to the blogosphere.
I do accept as true with all the concepts you’ve offered
ReplyDeleteon 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?
스포츠토토
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안전놀이터 모음
I think there are lots of more enjoyable instances ahead for individuals who take a look
ReplyDeleteat your blog post.휴게텔
Yeah bookmaking this wasn't a bad determination outstanding post!
Wow that was odd. I just wrote an really long comment but after I
ReplyDeleteclicked submit my comment didn't show up. Grrrr... well I'm
not writing all that over again. Regardless, just wanted to say excellent blog!
부산달리기
Good day! I could have sworn I've been to this website
ReplyDeletebefore 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 출장안마
It’s hard to come by knowledgeable people for this subject, but you sound like you know what you’re talking about!
ReplyDeleteThanks카지노사이트
I truly appreciate this article.Really looking forward to read more. Great. Satta Matka
ReplyDelete
ReplyDelete39 years old Video Producer Kristopher from La Prairie, has
hobbies and interests for example model railways,
and scrabble. that covered going to Tyre.
스포츠토토
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.
ReplyDeletehttps://www.bignewsnetwork.com/news/270790674/who-are-the-most-successful-baseball-teams-of-all-time
ReplyDeleteNice post.Thank you for taking the time to publish this information very useful!
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. 먹튀검증사이트
ReplyDeleteThis 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
ReplyDeleteI 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스포츠토토 Howdy just wanted to give you a quick heads up.
ReplyDeleteThe 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
카지노사이트홈 I think this is among the most significant information for me.
ReplyDeleteAnd 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
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? 안전한 바카라사이트
ReplyDeleteIf some one wishes to be updated with most recent technologies afterward
ReplyDeletehe must be pay a quick visit this web site and
be up to date everyday.Click Here 인터넷경마
2JIYANGWOOK
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카지노사이트
The blog is instructive additionally Wow, great blog article 토토추천
ReplyDeleteYou obviously know what youre talking about 메이저사이트 Thank you for sharing your thoughts. I really appreciate your
ReplyDeleteWe are linking to this great post on our website Thank you for your always good posts 먹튀폴리스
ReplyDeleteExtremely 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 토토사이트검증
ReplyDeleteGreat information and it is also very well written 안전한놀이터 I will bookmark and comeback really the best on this valuable topic
ReplyDeleteI like to recommend exclusively fine plus 메이저검증업체 efficient information and facts, hence notice it: coryxkenshin merch
ReplyDeleteI finally found what I was looking for! I'm so happy. 메이저사이트
ReplyDeleteNice 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. 안전놀이터추천
ReplyDeleteFrom 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 토토사이트!!
ReplyDeleteWhen 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?
ReplyDeleteHello ! 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?
ReplyDeleteI 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!
ReplyDeleteHello, 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.
ReplyDeleteExcellent Blog! I would like to thank you for the efforts you have made in writing this post. Gained lots of knowledge.
ReplyDeleteBest Refrigerator Repair Service in Hyderabad
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.오공슬롯
ReplyDeleteWhat 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.
ReplyDeleteHello, I am one of the most impressed people in your article. 온라인바카라 If possible, please visit my website as well. Thank you.
ReplyDeleteI hope you can help me. I've been thinking about this for a long time, but I'm not getting it resolved.온카지노
ReplyDeleteYou 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. 바카라사이트
ReplyDeleteI 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. 메이저놀이터
ReplyDeleteYour 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.
ReplyDeleteYou 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. 토토사이트
ReplyDeleteThanks 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. 안전놀이터
ReplyDeleteRoyalcasino509
ReplyDeleteoncainven
ReplyDeleteI really enjoyed reading this article
ReplyDeleteReseller Hosting in Nepal: Unlocking Opportunities with the Best Web Hosting in Nepalweb hosting services in nepal
ReplyDeleteExperience 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.
ReplyDeletehttps://www.premgreen.com/sojat-ki-number-one-mehndi/
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