您需要参考 Bootstrap 来执行此操作。示例:
这是假设您有一个名为“QuestionController”的控制器、两个名为“Question”的文件夹和“QuestionsPartial”视图文件夹,在“Question”文件夹中有一个名为“QuestionView”的视图,以及一个名为“_questionResults”的局部视图"在“QuestionsPartial”文件夹中。
这将是你的观点:
@using PageResource = ProjectName.Resources.Question
@model ProjectName.Models.Question
@{
ViewBag.Title = PageResource.PageTitle;
}
<div>
@if(Model.Questions.Any())
{
using (Ajax.BeginForm("QuestionView", "Question", new AjaxOptions
{
UpdateTargetId = "questionList",
HttpMethod = "get",
LoadingElementId = "loading",
OnSuccess = "addPaginationStyle",
OnFailure = "failurePaging"
}))
{
<div id="questionList">
@{ Html.RenderPartial("QuestionsPartial/_questionResults", Model); }
</div>
}
}
else
{
<br/>
<p class="lead text-danger">@string.Format(PageResource.NoQuestionsFound)</p>
}
</div>
在你的部分视图中:
@using MvcPaging
@model ProjectName.Models.Question
@if (Model.TotalItemCount > 0)
{
<table class="table">
<thead>
<tr>
<th>Title</th>
<th>Question</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.Title</td>
<td>@item.Description</td> @* The actual question *@
</tr>
}
</tbody>
</table>
if (Model.HasNextPage || Model.HasPreviousPage)
{
<!-- Paging Bar -->
<div>
@Html.Raw(Ajax.Pager(
new Options
{
PageSize = Model.PageSize,
TotalItemCount = Model.TotalItemCount,
CurrentPage = Model.PageNumber,
ItemTexts = new ItemTexts { Next = "Next", Previous = "Previous", Page = "P" },
ItemIcon = new ItemIcon { First = "glyphicon glyphicon-backward", Previous = "glyphicon glyphicon-chevron-left", Next = "glyphicon glyphicon-chevron-right", Last = "glyphicon glyphicon-forward" },
Size = Size.normal,
Alignment = Alignment.centered,
IsShowControls = true,
IsShowFirstLast = true,
},
new AjaxOptions
{
UpdateTargetId = "questionList",
OnSuccess = "addPaginationStyle",
OnFailure = "failurePaging"
}, new { controller = "Question", action = "QuestionView", questionId = Model.QuestionId }))
<div class="well">
Showing <span class="badge">@Model.ItemStart</span> to <span class="badge">@Model.ItemEnd</span>
of <span class="badge">@Model.TotalItemCount</span> entries.
</div>
</div>
}
}
将此添加到“共享”文件夹中的“_Layout.cshtml”视图,该文件夹位于“视图”文件夹内:
@Scripts.Render("~/bundles/bootstrap")
然后将其添加到 App_Start 文件夹内的“BundleConfig.cs”:
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
// other Bootstrap components you want, e.g.:
"~/Scripts/bootstrap-multiselect.js"));
编辑:添加了一些我忘记的 Javascript 函数!
将这些添加到“global.js”文件中:
$(document).ready(function () {
// Ajax.Pager method doesn't place the bootstrap class on the correct element
// Add pagination class to "ul" element and remove it from the "div" element
($('.pagination').length) {
addPaginationStyle();
});
function failurePaging() {
alert("Could not retrieve paged list.");
}
function addPaginationStyle() {
$('.pagination ul:first').addClass('pagination');
$('.pagination:first').removeClass();
}