服务器端分页MVC 6.0

问题描述 投票:0回答:2

我有带有 WCF 服务的 MVC 项目。

当我显示数据列表时,我确实想从数据库/服务加载所有内容并进行客户端分页。但我确实想要服务器端分页。如果我有100条记录,页面大小为10,那么当用户点击第1页时,它只会从数据库中检索前10条记录,如果用户点击第3页,那么它只会检索相应的10条记录。 我没有使用 Angular 或任何其他引导程序。

有人可以指导我怎么做吗?

  public ActionResult Index(int pageNo = 1)
    {
        ..
        ..
        ..      

        MyViewModel[] myViewModelListArray = MyService.GetData();           

        //when I create this PageList, BLL.GetData have to retreive all the records  to show more than a single page no. 
        //But if the BLL.GetData() was changed to retrieve a subset, then it only shows a single page no.
        //what I wanted to do is, show the correct no of pages (if there are 50 records, and pageSize is 10, then show 
        //page 1,2,3,4,5 and only retrieve 10 records at a time.
        PagedList<MyViewModel> pageList = new PagedList<<MyViewModel>(myViewModelListArray, pageNo, pageSizeListing);
        ..
        ..
        ..
        return View(pageList);
    }
c# pagination asp.net-core-mvc server-side
2个回答
2
投票

最好的方法是使用 LINQ to Entities 运算符 Skip & Take。

例如,前往页面

int items_per_page = 10;
MyViewModel[] myViewModelListArray = MyService.GetData().OrderBy(p => p.ID).Skip((pageNo - 1) * items_per_page).Take(items_per_page).ToArray();

注意:数据必须是有序的,因此页面具有一定的一致性(但我是通过任意字段 ID 做到的)。此外,一些数据库需要“order by”来应用“limit”或“top”(这就是 Take/Skip 的实现方式)。

我这么说是因为我不知道你是如何检索数据的。 但是,最好在 GetData 内的查询中包含分页,而不是使用 GetData 检索完整列表,然后过滤掉(这样您就不会检索不必要的数据)。


1
投票

将参数页面大小和页码添加到您的服务方法中,并使结果成为一个返回 TotalCount 和 List Items 的对象(Items 是当前页面上的项目)。然后您可以使用这些值来创建 PagedList。

在业务逻辑代码中,您将执行两项查询,一项查询项目数量,一项查询页面上的项目。

此外,如果您现在正在启动该项目,请帮自己一个忙,从您的架构中删除无用的 WCF 服务。

© www.soinside.com 2019 - 2024. All rights reserved.