[英]ASP MVC Paging with LINQ?
I have 100 record. 我有100条记录。 I want LINQ for this: 我想要LINQ:
int pageNumber = get from user; // for example 2 , 3 ,...
if pageNumber == 2
return records 20 to 29
Thanks! 谢谢!
What you want probably is the following: 您想要的可能是以下内容:
var itemsToShow = items.OrderBy(p => p.Id)
.Skip((currentPage - 1) * numPerPage)
.Take(numPerPage);
Where you are ordering pages by Id
property and you have variables currentPage
holding the number of the current page and numPerPage
holding the number of items per page. 在通过Id
属性对页面进行排序的位置上,您具有变量currentPage
以及当前页面的数量,而numPerPage
则包含每页的项目数。
You probably would like then to make a type containing the paging info to make your life easier. 然后,您可能希望创建一个包含分页信息的类型,以使您的生活更轻松。 Something like 就像是
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);
}
}
}
Then your currentPage
would be pagingInfo.CurrentPage
and your numPerPage
would be pagingInfo.ItemsPerPage
. 然后,您的currentPage
将是pagingInfo.CurrentPage
而您的numPerPage
将是pagingInfo.ItemsPerPage
。 In addition you have a property to get the total number of pages which can be useful. 此外,您还有一个属性可以获取总页数,这很有用。 This is a good approach so that you can transport information about paging on view models. 这是一种好方法,因此您可以传输有关视图模型上的页面调度的信息。
int Page = 1;
int RecordsPerPage = 10;
var q = yourQuery.Skip((Page - 1) * RecordsPerPage).Take(RecordsPerPage);
i suggest to use PagedList.MVC its a free library witch is available on Nuget: here is an example: this is going to be your action: 我建议使用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);
}
i`v set model for view as an IPagedList, this is the view: nice thing is that it will automaticlly generate page links. 我将视图的模型设置为IPagedList,这是视图:很好的是,它将自动生成页面链接。
<div class="pager">
@Html.PagedListPager(Model, page => Url.Action("Index", new { page }), PagedListRenderOptions.ClassicPlusFirstAndLast)
</div>
its customizable (via css). 其可自定义(通过CSS)。 this is the nuget page: PagedList.MVC nuget page 这是nuget页面: PagedList.MVC nuget页面
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.