用我的ViewModels实现IPagedList

本文关键字:IPagedList 实现 ViewModels 我的 | 更新日期: 2023-09-27 17:51:17

我使用NuGet PagedList。Mvc在我的ASP。. NET MVC应用程序,我想返回到视图placesVM。ToPagedList (pageNumber pageSize)

我尝试使用PagedList<>而不是List<>。

我检查的例子,似乎不符合我的场景,还是他们?

下面是我的实际代码。

ViewModel

using PagedList;
using System.Collections.Generic;
namespace WhereWeDoIt.ViewModels
{
    public class PlacesIndexViewModel
    {
        public /*PagedList*/List<PlaceIndexViewModel> Places { get; set; }
        public string CurrentUserId { get; set; }
    }
}
控制器

public ActionResult Index(int? page)
{
    var config = new MapperConfiguration(cfg => cfg.CreateMap<Place, PlaceIndexViewModel>());
    var mapper = config.CreateMapper();
    var placesVm = new PlacesIndexViewModel { Places = new List<PlaceIndexViewModel>(), 
                                            CurrentUserId = User.Identity.GetUserId() };
    var placesBal = new PlaceBusinessLayer();
    var places = placesBal.GetAllPublic();
    placesVm.Places = mapper.Map<List<PlaceIndexViewModel>>(places);
    int pageSize = 3;
    int pageNumber = (page ?? 1);
    return View(placesVm/*.ToPagedList(pageNumber, pageSize)*/);
}

用我的ViewModels实现IPagedList

如果您正在将数据库中的记录映射到视图模型上,那么您需要使用StaticPagedList

总的来说,Stephen对你有一些好的观点。您的repo方法应该返回一个可查询对象,而不是一个列表,因为在应用任何分页逻辑之前,这确实会物化所有记录。但是,如果您随后使用AutoMapper将它们映射到视图模型上,同样的事情仍然会发生。相反,您必须首先限制您的可查询项:
var places = placesBal.GetAllPublic().Skip((pageNumber - 1) * pageSize).Take(pageSize);

您还需要一个单独的查询来获取总数。没有办法在一个查询中完成所有这些,但是计数查询速度很快。在这里,您不限制查询集,因为您需要的是总数,而不仅仅是当前页面上的总数。

var totalPlaces = placesBal.GetAllPublic().Count();

然后,映射它:

var mappedPlaces = mapper.Map<List<PlaceIndexViewModel>>(places);

在最后新建一个StaticPagedList实例之前:

placesVm.Places = new StaticPagedList<PlaceIndexViewModel>(mappedPlaces, pageNumber, pageSize, totalPlaces);