Bootstrap Pagination for ASP.NET GridView
2013-11-04 15:00
288 查看
源代码下载,请点击这里
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,
jQuery
BootPag jQuery Plugin
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.
4. Next let us create a web form with a gridview, and use bootpag plugin to generate pagination component for the gridview.
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.
That is all! Now run the project and view "Default.aspx" in browser to see the gridview working with Bootstrap Pagination component.
原文地址:
http://www.programming-free.com/2013/07/bootstrap-pagination-for-aspnet-gridview.html
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,
jQuery
BootPag jQuery Plugin
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.
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.
<!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.
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.
原文地址:
http://www.programming-free.com/2013/07/bootstrap-pagination-for-aspnet-gridview.html
相关文章推荐
- ASP.NET GridView的Bootstrap分页样式
- ASP.NET关于引用bootstrap.css导致Gridview Header无法居中
- ASP.NET GridView的Bootstrap分页样式
- ASP.NET GridView的Bootstrap分页样式
- ASP.NET: GridView CRUD using Twitter Bootstrap Modal Popup
- GridView Examples for ASP.NET 2.0
- ASP.NET: Display GridView Row Details in Modal Popup using Twitter Bootstrap
- ASP.NET GridView的Bootstrap分页样式
- 利用ASP.NET MVC和Bootstrap快速搭建个人博客之后台dataTable数据列表
- ASP.NET MVC+Bootstrap个人博客之文章打赏(六)
- 【ASP.NET】GridView与ObjectDataSource的使用
- ASP.net 多种方式读取GridView某行的值
- ASP.NET MVC Code and Slides for Best of Mix 09 Presentation
- ASP.NET2005 gridview中点击某行的任意位置选中某行 交替效果 变换鼠标手势
- asp.net GridView 72般绝技
- 使用ASP.NET 2.0中的GridView控件
- Asp.net 2.0 自定义控件开发[实现GridView多行表头固定表体滚动效果][示例代码下载]
- DynamicData for Asp.net Mvc留言本实例 下篇 更新
- “Razor” – a new view engine for ASP.NET
- Asp.net 2.0 自定义控件开发[创建自定义HeaderRow的GridView控件][示例代码下载]