使用我的 ViewModels 实现 IPagedList

Implementing IPagedList with my ViewModels

我在 ASP.NET MVC 应用程序上使用 NuGet PagedList.Mvc,我想 return 查看 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)*/);
}

如果您要将记录从数据库映射到视图模型,则需要利用 StaticPagedList

总的来说,斯蒂芬对你有一些好处。你的回购方法应该 return 一个可查询的,而不是一个列表,因为在你可以应用任何分页逻辑之前,它确实会具体化所有记录。但是,如果您随后使用 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);