我有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);
}
答案 0 :(得分:2)
最好的方法是使用LINQ to Entities运算符Skip&amp;取。
例如,到页面
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)。还有一些数据库需要&#39;按顺序排列。申请&#39;限制&#39;或者&#39; top&#39; (这是实施Take / Skip的方式)。
我这么说,因为我不知道你是如何检索数据的。 但是使用GetData检索完整列表然后过滤掉,最好在GetData内的查询中包含分页(这样你就不会检索不必要的数据)。
答案 1 :(得分:1)
将参数页面大小和页码添加到服务方法中,并使结果成为返回TotalCount和List Items(项目是当前页面上的项目)的对象。然后,您可以使用这些值来创建PagedList。
在您的业务逻辑代码中,您将对项目数量进行两次查询,对页面上的项目进行一次查询。
此外,如果您现在正在启动项目,请自行帮忙并从架构中删除无用的WCF服务。