【问题标题】:Server-Side Paging MVC 6.0服务器端分页 MVC 6.0
【发布时间】:2016-11-05 07:47:54
【问题描述】:

我有带有 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);
    }

【问题讨论】:

  • 您能否发布一些代码,向我们展示您已经尝试过但不起作用的内容?向大家展示你在什么样的环境中工作以及你正在使用的编码风格将有很长的路要走。
  • 请显示一些代码。您也可以尝试将 start 和 limit 传递给服务器,以便告诉服务器应该返回哪些特定的记录集。
  • @bogzy 如果我通过传入 PageSize 和 PageNo 来限制要返回的特定记录集,那么它只显示一个页面。

标签: c# asp.net-core-mvc paging server-side


【解决方案1】:

最好的方法是使用 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 内的查询中(这样您就不会检索不必要的数据)。

【讨论】:

    【解决方案2】:

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

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

    另外,如果您现在开始项目,请帮自己一个忙,从您的架构中删除无用的 WCF 服务。

    【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    相关资源
    最近更新 更多