[英]ASP MVC Paging with LINQ?
我有100條記錄。 我想要LINQ:
int pageNumber = get from user; // for example 2 , 3 ,...
if pageNumber == 2
return records 20 to 29
謝謝!
您想要的可能是以下內容:
var itemsToShow = items.OrderBy(p => p.Id)
.Skip((currentPage - 1) * numPerPage)
.Take(numPerPage);
在通過Id
屬性對頁面進行排序的位置上,您具有變量currentPage
以及當前頁面的數量,而numPerPage
則包含每頁的項目數。
然后,您可能希望創建一個包含分頁信息的類型,以使您的生活更輕松。 就像是
public class PagingInfo
{
public int ItemsPerPage { get; set; }
public int NumItems { get; set; }
public int CurrentPage { get; set; }
public int TotalPages
{
get
{
return Math.Ceiling((double)NumItems/ItemsPerPage);
}
}
}
然后,您的currentPage
將是pagingInfo.CurrentPage
而您的numPerPage
將是pagingInfo.ItemsPerPage
。 此外,您還有一個屬性可以獲取總頁數,這很有用。 這是一種好方法,因此您可以傳輸有關視圖模型上的頁面調度的信息。
int Page = 1;
int RecordsPerPage = 10;
var q = yourQuery.Skip((Page - 1) * RecordsPerPage).Take(RecordsPerPage);
我建議使用PagedList.MVC,它在Nuget上提供了一個免費的庫巫婆:這是一個示例:這將是您的操作:
public ActionResult Index(int page = 1)
{
//_db is my sample data context but paged list works for any IEnumerable
//since this is an extension method
var model =
_db.Comments
.OrderByDescending(c => c.Date)
.ToPagedList(page, 10);
return View(model);
}
我將視圖的模型設置為IPagedList,這是視圖:很好的是,它將自動生成頁面鏈接。
<div class="pager">
@Html.PagedListPager(Model, page => Url.Action("Index", new { page }), PagedListRenderOptions.ClassicPlusFirstAndLast)
</div>
其可自定義(通過CSS)。 這是nuget頁面: PagedList.MVC nuget頁面
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.