我该怎么做分页在ASP.NET MVC? [英] How do I do pagination in ASP.NET MVC?
问题描述
什么是最preferred并做分页在ASP.NET MVC最简单的方法?即什么是打破了一个列表分成几个可浏览页面的最简单的方法。
作为一个例子可以说我得到的元素列表,从这样的数据库/网关/存储库:
公众的ActionResult ListMyItems()
{
清单<项目>清单= ItemDB.GetListOfItems();
计算机[ITEMLIST] =清单; 返回查看();
}
为了简便起见,我想指定我为参数的行动只是一个页码。像这样的:
公众的ActionResult ListMyItems(INT页)
{
// ...
}
那么,什么是数据源?你的行动可以采取一些违约的论点,即
的ActionResult搜索(查询字符串,诠释了startIndex,诠释的pageSize){...}
在默认的路由设置,使startIndex是0,pageSize的是(说)20:
routes.MapRoute(搜索,搜索/ {查询} / {}了startIndex
新
{
控制器=家,行动=搜索,
的startIndex = 0,的pageSize = 20
});
要拆分的饲料,你可以使用LINQ很容易:
VAR页= source.Skip(的startIndex)。取(pageSize的);
(或者,如果你用PAGENUMBER而不是的startIndex做乘法)
使用LINQ-toSQL,EF,等等 - 这应该撰写下调至数据库,太
然后,您应该能够使用动作链接到下一个页面(等):
<%= Html.ActionLink(下一页,搜索,新{
查询,则startIndex = +了startIndex的pageSize,pageSize的})%GT;
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) {...}
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
});
To split the feed, you can use LINQ quite easily:
var page = source.Skip(startIndex).Take(pageSize);
(or do a multiplication if you use "pageNumber" rather than "startIndex")
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屋!