gpt4 book ai didi

c# - PagedList 和异步

转载 作者:可可西里 更新时间:2023-11-01 08:34:14 28 4
gpt4 key购买 nike

我在我的 View 中使用 PagedList,但我的脚手架 Controller 是使用这种默认索引操作生成的:

public async Task<ActionResult> Index()
{
return View(await db.Claimants.ToListAsync());
}

我没有找到 PagedList 与 async 一起工作的扩展。我的方法必须更改为如下形式:

public ActionResult Index(int? page)
{
var claimants = db.Claimants.OrderBy(b => b.Name);
var notNullPage = page ?? 1;
return View(claimants.ToPagedList(notNullPage, 50));
}

是否有合理的方式来处理 PagedList 和 async

最佳答案

Is there a reasonable way to work with PagedList and async?

是的。不会与 EF 开箱即用。但是,你可以获得 PagedList.EntityFramework它公开了一个 ToPagedListAsync:

public class PagedListExtended<T> : BasePagedList<T> 
{
private PagedListExtended()
{
}

public static async Task<IPagedList<T>> Create(IQueryable<T> superset, int pageNumber, int pageSize)
{
var list = new PagedListExtended<T>();
await list.Init(superset, pageNumber, pageSize);
return list;
}

async Task Init(IQueryable<T> superset, int pageNumber, int pageSize)
{
if (pageNumber < 1)
throw new ArgumentOutOfRangeException("pageNumber", pageNumber, "PageNumber cannot be below 1.");
if (pageSize < 1)
throw new ArgumentOutOfRangeException("pageSize", pageSize, "PageSize cannot be less than 1.");
TotalItemCount = superset == null ? 0 : await superset.CountAsync();
PageSize = pageSize;
PageNumber = pageNumber;
PageCount = TotalItemCount > 0 ? (int) Math.Ceiling(TotalItemCount/(double) PageSize) : 0;
HasPreviousPage = PageNumber > 1;
HasNextPage = PageNumber < PageCount;
IsFirstPage = PageNumber == 1;
IsLastPage = PageNumber >= PageCount;
FirstItemOnPage = (PageNumber - 1)*PageSize + 1;
var num = FirstItemOnPage + PageSize - 1;
LastItemOnPage = num > TotalItemCount ? TotalItemCount : num;
if (superset == null || TotalItemCount <= 0)
return;
Subset.AddRange(pageNumber == 1 ? await superset.Skip(0).Take(pageSize).ToListAsync() : await superset.Skip((pageNumber - 1)*pageSize).Take(pageSize).ToListAsync());
}
}

public static class PagedListExtendedExtensions
{
public static async Task<IPagedList<T>> ToPagedListAsync<T>(this IQueryable<T> superset, int pageNumber, int pageSize)
{
return await PagedListExtended<T>.Create(superset, pageNumber, pageSize);
}
}

关于c# - PagedList 和异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31574315/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com