Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write extension method for paging in mvc

i've define static class to enable paging :

public static class Pager
{
   public static IEnumerable<T> PageData<T>(this IEnumerable<T> source, int currentPage, int pageSize)
   {
       var sourceCopy = source.ToList();

       if (sourceCopy.Count() < pageSize)
       {
            return sourceCopy;
       }

       return sourceCopy.Skip((currentPage - 1) * pageSize).Take(pageSize);
   }
}

and i want in my controller to do like :

var pagedDataCourses = products.OrderBy(p => p.productName).PageData(currentPage, pageSize);

so where i can put that static class/method so i can get extension method for paging in all controller.

like image 656
Milan Mendpara Avatar asked Oct 09 '22 22:10

Milan Mendpara


1 Answers

public static IQueryable<T> Page<T>(this IQueryable<T> query, int page, int pageSize)
{
   int skip = Math.Max(pageSize * (page - 1), 0);
   return query.Skip(skip).Take(pageSize);
}

You will have to put it in the same namespace as where you are using the extension. Or us the "using" at the top of your .cs files

like image 168
stian.net Avatar answered Oct 12 '22 12:10

stian.net