how to write extension method for paging in mvc

拥有回忆 提交于 2020-01-24 04:14:05

问题


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.


回答1:


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




回答2:


Take a look at MVC contrib paging http://mvccontrib.codeplex.com/wikipage?title=Grid



来源:https://stackoverflow.com/questions/8970467/how-to-write-extension-method-for-paging-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!