简体   繁体   中英

Data paging in linq without removing records from the data source

EDIT

No need for an answer. To test how things worked, I removed the .Skip() from the LINQ query and it pages exactly how I expected it to.


My data paging is a bit of a mess. When I click on to page 2, rebinding the data source completely removes the first page of data.

So with 14 rows returned initially and a page size of 10 rows, I can click on page 2 where I correctly see the remaining 4 rows, but now I can no longer page because the preceding 10 rows have been removed from the data source.

Here's my code:

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

How can I keep the entirety of the data source but show only those that correspond to the selected page?

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

I think giving the PagedList library a try is worth a shot. It even has a published tutorial on how to page, sort and filter results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM