Cấp bậc tác giả:

DOTNET

Phân trang với Bootstrap Pagination cho ASP.NET GridView

Được viết bởi QuangIT ngày 03/09/2014 lúc 10:12 AM
Bootstrap cung cấp thành phần pagination trông đơn giản nhưng khó bỏ lỡ, dễ dàng mở rộng, và cung cấp khả năng nhấp chuột. Đây là thành phần tĩnh và rất ít plugin jQuery giúp đơn giản hóa việc phân trang. Trong bài này, tôi sẽ sử dụng BootPag jQuery plugin và thực hiện phân trang phía máy chủ trong ASP.Net GridView.
  • 0
  • 16226
Tải tệp tin: Click ở đây

Phân trang với Bootstrap Pagination cho ASP.NET GridView

bootstrap_pagination_gridview_1.png

jQuery Bootpag là plugin pagination bootstrap nâng cao. Rất dễ để thiết lập - chỉ phải thông qua chức năng callback và listen cho sự kiện trang. Bên trong chức năng đó, có thể cập nhật GridView với nội dung bằng cách thực hiện gọi phương thức ajax phía máy chủ web. 

1. Tạo ứng dụng web ASP.NET. Tải về:
bootstrap_pagination_gridview_2.png

2. Sử dụng tập tin csv với dữ liệu mẫu để hiển thị trên GridView. Tôi đã tạo ra tập tin csv và lưu trữ nó trong thư mục Project/App_Data. 

Chúng ta cần mô hình lớp để đại diện cho các cột trong file csv (country, revenue, salemanager, year). Tôi đang thực hiện phân trang phía máy chủ trong ví dụ này.

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;
        }        
    }
}

3. Tiếp theo chúng ta tạo ra mẫu web với GridView, và sử dụng bootpag plugin để tạo ra phân trang cho 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>

Bây giờ chúng ta có cái nhìn sâu hơn về jQuery. Ban đầu khi tải trang, gọi ajax sẽ được thực hiện với phương thức phía máy chủ được gọi, GetTotalPageCount - phương thức này tìm nạp tổng số bảng ghi chứa trong tập tin csv khi trang tải ban đầu. Điều này là cần thiết bởi vì chúng ta phải thông qua tổng số đầu vào cho các plugin để tạo ra danh sách điều khiển phân trang dựa trên bootpag (tùy chọn: tổng số). GridView được nạp với năm bảng ghi đầu tiên trên trang tải từ phía máy chủ và trên tất cả các nhấp chuột trên điều khiển phân trang, gọi ajax được thực hiện với phương thức phía máy chủ gọi, GetGridData với số trang hiện tại như tham số - phương thức này là chịu trách nhiệm cho việc lấy bảng ghi từ file csv dựa trên số trang hiện tại. 

Lưu ý rằng GridView có mẫu phân trang, trong đó thẻ div với id "page-selection" được đặt.. 

4. Bước cuối cùng là tải GridView trên Page_Load và xác định phương thức phía máy chủ Web để thực hiện gọi jQuery Ajax trong tập tin behind code

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;
        }
    }
}

Bây giờ chạy Project và xem "default.aspx" trong trình duyệt để xem GridView làm việc với các thành phần Bootstrap Phân trang như thế nào.

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML