Showing posts with label PagedList. Show all posts
Showing posts with label PagedList. Show all posts

Tuesday, April 21, 2015

Paged List for WebAPI

One of my favorite quotes is "there is nothing as embarrassing as yesterday's code." I blogged about a paged list class a while back, but I no longer like that implementation...so here is a new one that includes WebAPI serialization support!

...but why is this useful?

You can use the simple IPagedList interface to pass paged data around all of your application, and then any object returned from your WebAPI that implements IPagedList will be automatically serialized for you. This allows you to create very consistent APIs that support paging.

IPagedList Interfaces

public interface IPagedList
{
    int PageIndex { get; }
 
    int PageSize { get; }
 
    int TotalCount { get; }
 
    IList List { get; }
}
 
public interface IPagedList<T> : IPagedList
{
    new IList<T> List { get; }
}

Monday, January 20, 2014

Serializable PagedList for .NET

Developers have to page through data sets every day. For example: bring me back 101-200 (or the second page) of 1,000 results. So how do we move that data between our data, service, and UI and layers? That is where a PagedList collection comes in!

The sooner you add this to your core library the better off your whole team will all be. No more creating extra models to hold page data, no more loading extra results just to pass that data around and then not consume it, and no more reinventing the wheel over and over! I really wish that Microsoft would add a native paged list to the .NET framework; but until that time we just have to roll our own.

So what are the qualities of a good PagedList?

  • It should be generic collection.
  • It should support a non generic interface.
  • It should be easy to serialize.

Yes, there is already a PagedList project on NuGet and GitHub. Please do not misunderstand me, that is a good project! However the code below is a bit more light weight and easier to serialize. Additionally I prefer the extension methods of ToPagedList and TakePage; where the former creates a list as a page, and the latter selects a page from a super-set.

But hey, you can decide which you prefer! :)

Interfaces

public interface IPagedList
{
    ICollection Items { get; }
    int Count { get; }
    int PageIndex { get; }
    int PageSize { get; }
    int TotalCount { get; }
    int TotalPages { get; }
    bool HasPreviousPage { get; }
    bool HasNextPage { get; }
}
 
public interface IPagedList<T>: IPagedList
{
    new ICollection<T> Items { get; }
}
Real Time Web Analytics