且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我该怎么做分页在ASP.NET MVC?

更新时间:2023-02-25 22:47:41

那么,什么是数据源?你的行动可以采取一些违约的论点,即

 的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 }) %>