Asp Core, How to create Paging?

≯℡__Kan透↙ 提交于 2019-12-10 22:12:28

问题


I want to use PagingList<T>.CreateAsync() to create PagedList in index view but get below error in line var modelPaging = await PagingList<UserListViewModel>.CreateAsync(model, 10, page);:

can not convert from system.collection.Generic.List<> to system.linq.IorderedQueryable<>

my action code :

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

and 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; }

}

What changes should I make in my code?

I asked another question on this subject here link


回答1:


The error is pretty clear that tells you CreateAsync needs IOrderedQueryable but you are giving the data already retrieved from database. You should pass the query itself. Remove 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);

The main purpose of PagingList apply the pagination directly from database instead of in-memory.



来源:https://stackoverflow.com/questions/48354813/asp-core-how-to-create-paging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!