linq中的数据分页,无需从数据源中删除记录

时间:2017-08-17 14:38:19

标签: c# linq aspxgridview

修改

无需答案。为了测试事情是如何工作的,我从LINQ查询中删除了private void LoadVouchers(int page) { var ViewModel = new List<ListVouchersViewModel>(); var PageSize = gvVouchers.PageSize; // Value = 10. var Skip = page * PageSize; // Value = 1 * 10 = 10 so skip 10 rows. int SupplierId = int.TryParse(hdSupplierId.Value, out SupplierId) ? SupplierId : 0; using (ApplicationDbContext Context = new ApplicationDbContext()) { var Vouchers = Context.Vouchers.Where(x => x.SupplierId == SupplierId && !x.Deleted) .OrderBy(x => x.DateIssued) .Skip(Skip); foreach (var Voucher in Vouchers) { // Add a new ListVoucherViewModel to the list. } } gvVouchers.DataSource = ViewModel; gvVouchers.DataBind(); } ,并且它的页面完全符合我的预期。

我的数据分页有点混乱。当我点击第2页时,重新绑定数据源会完全删除第一页数据。

因此,最初返回14行,页面大小为10行,我可以单击第2页,我正确地看到剩余的4行,但现在我无法再页面,因为前面的10行已从数据中删除源。

这是我的代码:

customcharts.js

如何保留整个数据源,但只显示与所选页面对应的数据源?

2 个答案:

答案 0 :(得分:0)

private void LoadVouchers(int page)
{
    var ViewModel = new List<ListVouchersViewModel>();
    var PageSize = gvVouchers.PageSize; // Value = 10.
    var Skip = page * PageSize; // Value = 1 * 10 = 10 so skip 10 rows.

    int SupplierId = int.TryParse(hdSupplierId.Value, out SupplierId) ? SupplierId : 0;
    int totalRowCount = 0;
    using (ApplicationDbContext Context = new ApplicationDbContext())
    {
        totalRowCount = Context.Vouchers.Count();
        var Vouchers = Context.Vouchers.Where(x => x.SupplierId == SupplierId && !x.Deleted)
                                       .OrderBy(x => x.DateIssued)
                                       .Skip(Skip);

        foreach (var Voucher in Vouchers)
        {
            // Add a new ListVoucherViewModel to the list.
        }
    }

    gvVouchers.DataSource = ViewModel;
    gvVouchers.VirtualItemCount = totalRowCount;
    gvVouchers.PageIndex = page;
    gvVouchers.DataBind();
}

答案 1 :(得分:0)

我认为试试PagedList库值得一试。它甚至已发布tutorial有关如何分页,排序和过滤结果的信息。