asp.netasp.net-mvcpaginationasp.net-core-mvc

Asp Core, How to create Paging?


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


Solution

  • 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.