Skip to content

[Netcore] 用bootcss实作数据分页功能

Jinxin Chen edited this page Dec 11, 2019 · 1 revision

创建支持分页的模板类:

public class PaginatedList<T> : List<T>
{
    public int PageIndex { get; private set; }
    public int TotalPages { get; private set; }

    public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
    {
        PageIndex = pageIndex;
        TotalPages = (int)Math.Ceiling(count / (double)pageSize);

        this.AddRange(items);
    }

    public bool HasPreviousPage
    {
        get
        {
            return (PageIndex > 1);
        }
    }

    public bool HasNextPage
    {
        get
        {
            return (PageIndex < TotalPages);
        }
    }

    public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
    {
        var count = await source.CountAsync();
        var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
        return new PaginatedList<T>(items, count, pageIndex, pageSize);
    }
}

Controller:

view中分页的实作:

@{
    var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
    var nextDisabled = !Model.HasNextPage ? "disabled" : "";
    var pageCount = 9;
}
<nav aria-label="..." class="text-center">
    <ul class="pagination">
        <li><a class="btn btn-default @prevDisabled"  asp-route-page="@(Model.PageIndex - 1)" aria-label="Previous"><span aria-hidden="true">«</span></a></li>

        @for(var begin = Math.Max(1, Model.PageIndex - (int)Math.Floor((double)pageCount / 2)); begin < Math.Min(Model.TotalPages, Model.PageIndex + (int)Math.Ceiling((double)pageCount / 2)); begin++ )
        {
            var active = begin == Model.PageIndex ? "active" : "";
            <li class="@active"><a asp-route-page="@begin">@begin<span class="sr-only">(current)</span></a></li>
        }
        <li><a class="btn btn-default @nextDisabled" asp-route-page="@(Model.PageIndex + 1)" aria-label="Next"><span aria-hidden="true">»</span></a></li>
    </ul>
</nav>

参照:https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page

Clone this wiki locally