要自定义ASP.NET MVC分页控件,请按照以下步骤操作:
首先,创建一个新的视图模型类,该类将包含分页所需的所有属性和方法。例如:
public class CustomPaginationViewModel
{
public int CurrentPage { get; set; }
public int TotalPages { get; set; }
public int ItemsPerPage { get; set; }
public int TotalItems { get; set; }
public string PaginationUrl { get; set; }
public CustomPaginationViewModel(int currentPage, int totalPages, int itemsPerPage, int totalItems)
{
CurrentPage = currentPage;
TotalPages = totalPages;
ItemsPerPage = itemsPerPage;
TotalItems = totalItems;
PaginationUrl = Url.Action("Index", "Home", new { page = currentPage });
}
public IEnumerable<SelectListItem> PageNumbers()
{
var pageNumbers = Enumerable.Range(1, TotalPages).ToList();
return pageNumbers.Select(number => new SelectListItem
{
Value = number.ToString(),
Text = number.ToString()
});
}
}
接下来,创建一个新的视图,该视图将用于显示分页控件。例如,在Views/Shared
文件夹下创建一个名为_CustomPagination.cshtml
的文件,并添加以下代码:
@model CustomPaginationViewModel
<nav aria-label="Page navigation">
<ul class="pagination">
<li class="page-item @(Model.CurrentPage == 1 ? "disabled" : "")">
<a class="page-link" href="@Model.PaginationUrl" aria-label="Previous">@Html.IconFor("ArrowLeft")</a>
</li>
@foreach (var pageNumber in Model.PageNumbers())
{
<li class="page-item @(Model.CurrentPage == pageNumber.Value ? "active" : "")">
<a class="page-link" href="@Model.PaginationUrl?page=@pageNumber.Value">@pageNumber.Text</a>
</li>
}
<li class="page-item @(Model.CurrentPage == Model.TotalPages ? "disabled" : "")">
<a class="page-link" href="@Model.PaginationUrl?page=@(Model.CurrentPage + 1)" aria-label="Next">@Html.IconFor("ArrowRight")</a>
</li>
</ul>
</nav>
现在,您可以在控制器中使用自定义分页视图模型来处理分页逻辑。例如,在HomeController
中:
public ActionResult Index(int page = 1, int itemsPerPage = 10)
{
var totalItems = // 获取总项目数
var totalPages = (int)Math.Ceiling((double)totalItems / itemsPerPage);
var customPaginationViewModel = new CustomPaginationViewModel(page, totalPages, itemsPerPage, totalItems);
var items = // 获取当前页的项目列表
return View(new { items, customPaginationViewModel });
}
最后,在视图中使用自定义分页视图来显示分页控件。例如,在Index.cshtml
中:
@model YourNamespace.ViewModels.CustomPaginationViewModel
@Html.Partial("_CustomPagination", Model)
<!-- 显示项目列表 -->
现在,您已经成功创建了一个自定义的ASP.NET MVC分页控件。您可以根据需要进一步自定义该控件的外观和行为。