如何用“页面”限制显示的数据?

时间:2016-10-03 00:26:27

标签: c# asp.net-mvc

我有一个包含许多数据行的列表。我通过table-tags列出它们(参见代码),这是一个很长的列表。

但是,我如何限制它们,例如每个“页面”最多10个数据行,底部有一个小的“上一个/下一个”按钮列出/导航到下一个10个数据行(like google search-pages where it have the best place to dump bodies


apply from 'https://raw.githubusercontent.com/gradle-fury/gradle-fury/master/gradle/site.gradle'

1 个答案:

答案 0 :(得分:2)

您必须使用Paging,它一次只会显示一些记录,并且在用户可以选择导航的记录下方,就像Google搜索一样,您还必须更改控制器以仅检索正在记录的记录数量显示以避免在不需要的情况下访问数据库。

首先,点击工具打开NuGet Package Manager控制台 - > NuGet包管理器 - >包管理器控制台

然后输入以下命令

Install-Package MVC4.Paging

这将安装一个库,用于在表格下方绘制分页控件

打开您的视图并添加以下代码

@using MvcPaging
@model IPagedList<Your Model Class>

Put here your table that lists the items

<div class="pager">
    @Html.Raw(Ajax.Pager(
            new Options
            {
                PageSize = Model.PageSize,
                TotalItemCount = Model.TotalItemCount,
                CurrentPage = Model.PageNumber,
                ItemTexts = new ItemTexts() { Next = "Next", Previous = "Previous", Page = "" },
                ItemIcon = new ItemIcon() { First = "icon-backward", Previous = "icon-chevron-left", Next = "icon-chevron-right", Last = "icon-forward" },
                TooltipTitles = new TooltipTitles() { Next = "Next page", Previous = "Previous page", Page = "Page {0}." },
                Size = Size.normal,
                Alignment = Alignment.centered,
                IsShowControls = true,
                IsShowFirstLast = true,
                CssClass = ""
            },
            new AjaxOptions
            {
                HttpMethod = "post",
            }, new { controller = "YourController", action = "YourAction" }))
</div>

<link href="~/Content/paging.css" rel="stylesheet" />

现在,您必须将控制器操作更改为

      using MvcPaging;

      public ActionResult Index(int? page) {
            int currentPageIndex = page.HasValue ? page.Value : 1;

            var results = db.Reviews.Include(m => m.User);
            results = results.OrderBy(a => a.Id);

            var totalCount = results.Count();
            var pagedResults = results.ToPagedList(currentPageIndex, defaultPageSize, totalCount);

        return View(pagedResults ;           
       }