I want to return the current pages and total pages form a generic method.
The implementation of the generic function is done as:
public class PaginatedList<T> : List<T>
{
public int PageIndex { get; set; }
public int TotalPages { get; set; }
public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
this.AddRange(items);
}
public bool HasPreviousPage
{
get
{
return (PageIndex > 1);
}
}
public bool HasNextPage
{
get
{
return (PageIndex < TotalPages);
}
}
public static async Task<PaginatedList<T>> CreateAsync(
IQueryable<T> source, int pageIndex, int pageSize)
{
var count = await source.CountAsync();
var items = await source.Skip(
(pageIndex - 1) * pageSize)
.Take(pageSize).ToListAsync();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
}
However, this function does not return the PageIndex
and TotalPages
to the calling function.
It always returns the items
list.
I am calling the method as:
public async Task<IActionResult> UserActivityList(string currentFilter,
string searchString, int? pageIndex, int pageSize = 10)
{
if (searchString != null)
{
pageIndex = 1;
}
else
{
searchString = currentFilter;
}
string CurrentFilter = searchString;
IQueryable<UserActivityList> results = _logContext.UserActivityLists;
if (!string.IsNullOrEmpty(searchString))
{
results = results.Where(s => s.Name.Contains(searchString));
}
var UserActivityLists = await PaginatedList<UserActivityList>.CreateAsync(results.AsNoTracking(), pageIndex ?? 1, pageSize);
return Ok(UserActivityLists);
}
The value of UserActivityList
, I have formatted the output to JSON, while am calling through a PostMan.
[
{
"id": 2186,
"name": "abc cbc"
},
{
"id": 2152,
"name": "def efg"
},
{
"id": 2238,
"name": "kgh tbf"
},
{
"id": 2172,
"name": "loc tbh"
},
{
"id": 1651,
"name": "abc abc"
}
]
What is the reason the PaginatedList
not returning other property? What is the thing I am missing here?