简体   繁体   中英

ASP MVC Paging with LINQ?

I have 100 record. I want LINQ for this:

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.

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 . 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:

 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.

<div class="pager">
    @Html.PagedListPager(Model, page => Url.Action("Index", new { page }),    PagedListRenderOptions.ClassicPlusFirstAndLast)
</div>

its customizable (via css). this is the nuget page: PagedList.MVC nuget page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM