您是否考虑过使用 PagedList 库进行分页?您所要做的就是在 ASP.NET MVC 应用程序中引用 PagedList 库
要安装 PagedList.Mvc,请在包管理器控制台中运行以下命令。您也可以使用 NuGet 来获取此包。
PM> Install-Package PagedList.Mvc
你的视图模型
public class QuestionViewModel
{
public int QuestionId { get; set; }
public string QuestionName { get; set; }
}
在您的控制器中,引用 PagedList
using PagedList;
and the Index method of your controller will be something like
public ActionResult Index(int? page)
{
var questions = new[] {
new QuestionViewModel { QuestionId = 1, QuestionName = "Question 1" },
new QuestionViewModel { QuestionId = 1, QuestionName = "Question 2" },
new QuestionViewModel { QuestionId = 1, QuestionName = "Question 3" },
new QuestionViewModel { QuestionId = 1, QuestionName = "Question 4" }
};
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(questions.ToPagedList(pageNumber, pageSize));
}
和你的索引视图
@model PagedList.IPagedList<ViewModel.QuestionViewModel>
@using PagedList.Mvc;
<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />
<table>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.QuestionId)
</td>
<td>
@Html.DisplayFor(modelItem => item.QuestionName)
</td>
</tr>
}
</table>
<br />
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
@Html.PagedListPager( Model, page => Url.Action("Index", new { page }) )
结果屏幕看起来像