Vex
Vex

Reputation: 1239

MVC3 paging and sorting without grid?

I was wondering if it's possible to implement 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?

Upvotes: 0

Views: 2181

Answers (4)

Ray Cheng
Ray Cheng

Reputation: 12566

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.

Upvotes: 1

Jason Evans
Jason Evans

Reputation: 29186

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);

Upvotes: 2

Dmitry Golubets
Dmitry Golubets

Reputation: 570

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.

Upvotes: 2

Chris Snowden
Chris Snowden

Reputation: 5002

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.

Upvotes: 1

Related Questions