Asp Core,如何创建分页?

时间:2018-01-20 10:05:36

标签: asp.net asp.net-mvc asp.net-core-mvc paging

我想使用PagingList<T>.CreateAsync()在索引视图中创建PagedList但在行var modelPaging = await PagingList<UserListViewModel>.CreateAsync(model, 10, page);中得到以下错误:

  

无法转换为system.collection.Generic.List&lt;&gt; to system.linq.IorderedQueryable&lt;&gt;

我的操作代码:

    [HttpGet]
    public async Task<IActionResult> Index(int page = 1)
    {

        List<UserListViewModel> model = new List<UserListViewModel>();
        model = _userManager.Users.AsNoTracking().Select(u => new UserListViewModel
        {
            Id = u.Id,
            FullName = u.FirstName + " " + u.LastName,
            Email = u.Email
        }).OrderBy(u => u.Id).ToList();
        var modelPaging = await PagingList<UserListViewModel>.CreateAsync(model, 10, page);

        return View(modelPaging);
    }

和UserListViewModel Viewmodel:

public class UserListViewModel
{

    public string Id { get; set; }

    public string FullName { get; set; }

    public string Email { get; set; }

    public string RoleName { get; set; }

}

我应该在代码中进行哪些更改?

我在这里问了另一个关于这个主题的问题link

1 个答案:

答案 0 :(得分:1)

错误非常清楚,告诉您CreateAsync需要IOrderedQueryable,但您提供的数据已经从数据库中检索过。您应该自己传递查询。删除ToList;

var query = _userManager.Users.AsNoTracking().Select(u => new UserListViewModel
{
    Id = u.Id,
    FullName = u.FirstName + " " + u.LastName,
    Email = u.Email
}).OrderBy(u => u.Id);
var modelPaging = await PagingList<UserListViewModel>.CreateAsync(query, 10, page);

PagingList的主要目的是直接从数据库而不是内存中应用分页。