When you serialize IPagedList it serializes the contents/data of the requested page and not the meta data (i.e. FirstItemOnPage, HasNextPage, etc. properties) will be lost.
So to overcome this issue you can create an anonymous class like the following which will have two properties
- items holds current page contents
- metaData holds super list metadata.
So change first part of your code to:
var list = new List<int>(Enumerable.Range(1, 1000));
var paged = list.AsQueryable().ToPagedList(3, 10);
var pagedWithMetaData = new { items = paged, metaData = paged.GetMetaData() };
then serialize that object
//Serialize
var json = JsonConvert.SerializeObject(pagedWithMetaData);
this will generate a sub-list with the metaData for your example it is like following:
{"items":[21,22,23,24,25,26,27,28,29,30],"metaData":{"PageCount":100,"TotalItemCount":1000,"PageNumber":3,"PageSize":10,"HasPreviousPage":true,"HasNextPage":true,"IsFirstPage":false,"IsLastPage":false,"FirstItemOnPage":21,"LastItemOnPage":30}}
now to deserialize you need to create three classes:
PaginationMetaData class to encapsulate the meta-data so when we deserialize the sub list it's metadata will be deserialzed to this type.
PaginationEntityClass where T : class class to encapsulate the anonymous class so when we deserialize the sub list its content and metadata will be deserialzed to this type.
PaginationEntityStruct where T : struct same as PaginationEntityClass but T here is a struct so it hold struct types instead of classes like your case for int.
So these three classes will as follow:
public class PaginationMetaData
{
public int FirstItemOnPage { get; set; }
public bool HasNextPage { get; set; }
public bool HasPreviousPage { get; set; }
public bool IsFirstPage { get; set; }
public bool IsLastPage { get; set; }
public int LastItemOnPage { get; set; }
public int PageCount { get; set; }
public int PageNumber { get; set; }
public int PageSize { get; set; }
public int TotalItemCount { get; set; }
}
public class PaginationEntityClass<T> where T : class
{
public PaginationEntityClass()
{
Items = new List<T>();
}
public IEnumerable<T> Items { get; set; }
public PaginationMetaData MetaData { get; set; }
}
public class PaginationEntityStruct<T> where T : struct
{
public PaginationEntityStruct()
{
Items = new List<T>();
}
public IEnumerable<T> Items { get; set; }
public PaginationMetaData MetaData { get; set; }
}
Now to deserialize you need just to deserialize to PaginationEntityStruct of integers then use the second constructor overload of StaticPagedList class (class comes with PagedList package) to recreate the subclass with metadata.
//Deserialize
var result = JsonConvert.DeserializeObject<PaginationEntityStruct<int>>(json);
StaticPagedList<int> lst = new StaticPagedList<int>(
result.Items,
result.MetaData.PageNumber,
result.MetaData.PageSize,
result.MetaData.TotalItemCount);