本文介绍了PagedList和异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在视图中使用PagedList,但是我的脚手架控制器是使用这种默认的Index Action生成的:
I'm using PagedList in my Views, but my scaffolded Controller is generated with this kind of default Index Action:
public async Task<ActionResult> Index()
{
return View(await db.Claimants.ToListAsync());
}
我找不到用于async
的PagedList扩展名.我的方法必须更改为如下形式:
I didn't find an extension for PagedList to work with async
. My methods have to be changed to a form like this:
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
:
Yes. Doesn't come out of the box with EF. But, you can get PagedList.EntityFramework
which exposes a 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);
}
}
这篇关于PagedList和异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!