开发者

MVC3 paging and sorting without grid?

开发者 https://www.devze.com 2023-03-22 19:22 出处:网络
I was wondering if it\'s possible to imple开发者_开发技巧ment paging and sorting of data using a @foreach Razor syntax instead of using a specific Grid control.

I was wondering if it's possible to imple开发者_开发技巧ment paging and sorting of data using a @foreach Razor syntax instead of using a specific Grid control.

Would it be difficult to implement? Should I stick to existing Grid solutions instead, such as WebGrid or MVCContrib grid?


I wrote an extension method for pagin my lists:

public static class DataPager
    {
        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);
        }
    }

Might be useful for you e.g.

    var courses = List<Courses>(); // Get courses somehow...

    int currentPage = 2;
    int pageSize = 5;

var pagedCourses = courses.OrderBy(c => c.Course.Title).PageData(currentPage, pageSize);


Important note to Jason's answer.

You should not use ToList method as it will negatively impact memory consumption and overall performance.

You should also check if IEnumerable object is IQueryable indeed and cast it to latter type before using extension methods Skip and Take. This will ensure the Query provider will take care of generating appropriate sql to select from the database instead of iterating over all records.


If you use LINQ then you can use OrderBy and ThenBy methods for sorting and Skip and Take methods for paging. If you do this in your repository or Controller on an IQueryable you can ensure that only the data needed is pulled back rather than pulling all and then sorting.


I don't think the OP is asking for server side code. you can use tablesorter for sorting. as for paging, i would suggest to append page number on URL and limit your data on server side.

0

精彩评论

暂无评论...
验证码 换一张
取 消