有关如何以最简单的方式在mvc网格中进行分页的任何建议吗?请指出示例代码,如果有的话
答案 0 :(得分:2)
丽兹,
我认为这个问题已经被提出,但这是我所指的问题:Paging & Sorting grids with ASP.Net MVC
此外,这是一个非常简洁的教程,介绍如何执行此操作:
http://xlib.wordpress.com/2009/06/29/asp-net-mvc-grid-%E2%80%93-part-2-paging/
以上链接中的一些片段:
使用此选项可在页面上获取选择器,以允许用户确定每页显示的行数:
<%= Html.DropDownList("pageSize", CustomerController.PageSizeSelectList(), new { onchange = "onPageSizeChange()" })%> rows per page
然后在自定义页面控制器中编写此代码:
public static SelectList PageSizeSelectList()
{
var pageSizes = new List {"1", "2", "5", "10", "100"};
return new SelectList(pageSizes, "Value");
}
现在将JavaScript添加到页面中:
//Set hidden variable to go to next/prev/last/first page and submit the form
function goToPage(pageIndex) {
$("#currentPage").val(pageIndex);
$("#gridAction").val("CurrentPageChanged");
submitForm();
}
//Set action performed in hidden variable. When PageSize changes - PageIndex needs to be
//reset to 1. This logic will go on the server side.
function onPageSizeChange(pageIndex) {
$("#gridAction").val("PageSizeChanged");
submitForm();
}
function submitForm() {
var form = $("#grid").parents("form:first");
form.submit();
}
然后更新您的页面控制器以执行分页:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult List(int currentPage, int pageSize, string gridAction)
{
//Do logic depending on what action was performed
if (gridAction == "PageSizeChanged")
currentPage = 1;
//Check if there are no results. In this case return empty list.
IQueryable query = _customerService.GetQueryable();
int totalRows = query.Count();
if (totalRows==0)
return View(new List());
int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
if (totalPages != 1)
{
//use LINQ to perform paging
query = query.Skip((currentPage - 1) * pageSize)
.Take(pageSize);
}
//Update ViewData collection to display pager stats and pager controls
UpdatePagerViewData(totalPages, totalRows, currentPage, pageSize);
List customers = query.ToList();
return View(customers);
}
我希望这有帮助,