如何在 ASP.NET MVC 中进行分页? [英] How do I do pagination in ASP.NET MVC?
问题描述
在 ASP.NET MVC 中进行分页的最首选和最简单的方法是什么?IE.将列表分解为多个可浏览页面的最简单方法是什么?
What is the most preferred and easiest way to do pagination in ASP.NET MVC? I.e. what is the easiest way to break up a list into several browsable pages.
举个例子,假设我从数据库/网关/存储库中获取元素列表,如下所示:
As an example lets say I get a list of elements from a database/gateway/repository like this:
public ActionResult ListMyItems()
{
List<Item> list = ItemDB.GetListOfItems();
ViewData["ItemList"] = list;
return View();
}
为简单起见,我只想为我的操作指定一个页码作为参数.像这样:
For simplicity's sake I'd like to specify just a page number for my action as parameter. Like this:
public ActionResult ListMyItems(int page)
{
//...
}
推荐答案
那么,数据源是什么?您的操作可能需要一些默认参数,即
Well, what is the data source? Your action could take a few defaulted arguments, i.e.
ActionResult Search(string query, int startIndex, int pageSize) {...}
在路由设置中默认设置为 startIndex 为 0,pageSize 为(例如)20:
defaulted in the routes setup so that startIndex is 0 and pageSize is (say) 20:
routes.MapRoute("Search", "Search/{query}/{startIndex}",
new
{
controller = "Home", action = "Search",
startIndex = 0, pageSize = 20
});
要拆分提要,您可以很容易地使用 LINQ:
To split the feed, you can use LINQ quite easily:
var page = source.Skip(startIndex).Take(pageSize);
(或者如果你使用pageNumber"而不是startIndex"进行乘法)
(or do a multiplication if you use "pageNumber" rather than "startIndex")
使用 LINQ-toSQL、EF 等 - 这也应该组合"到数据库中.
With LINQ-toSQL, EF, etc - this should "compose" down to the database, too.
然后您应该能够使用操作链接到下一页(等):
You should then be able to use action-links to the next page (etc):
<%=Html.ActionLink("next page", "Search", new {
query, startIndex = startIndex + pageSize, pageSize }) %>
这篇关于如何在 ASP.NET MVC 中进行分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!