I have a small application that displays a list of shortURLs to a user. I'm using ASP.NET MVC3, Entity Framework, and an Oracle backend. I'm also using the PagedList library by Troy Goode (https://github.com/TroyGoode/PagedList)
I want the user to see the very last entry first, similar to how blog comments are ordered. To do this I added an "orderby descending" clause to the LINQ statement:
var links = from l in db.LINKS
orderby l.ID descending
select l;
In debug the "links" object is ordered as expected (in descending order, by the primary key "ID").
Now I want to pass this list of links to the view using the .toPagedList() method:
int pageSize = 3;
int pageNumber = (page ?? 1); // "page" comes from the request, if null set to 1
return View(links.ToPagedList(pageNumber, pageSize));
This works great if I only have 3 records (refer to "pageSize" above). However, when I add a 4th record I get unexpected behavior. Because I have the pageSize set to 3, adding a fourth record means there will be 2 pages. I would expect the ordering to be as follows:
Page 1:
ID: 4
ID: 3
ID: 2
Page 2:
ID: 1
That is not the case, what actually happens is this:
Page 1:
ID: 3
ID: 2
ID: 1
Page 2:
ID: 4
So my question, what the heck am I doing wrong here? Why is PagedList not following the order defined by the "orderby l.ID descending" expression in the LINQ statement? It is baffling to me because in the debugger it is clear that the "links" object is ordered properly before the .toPagedLIst() is used on it.
Any help is greatly appreciated!
You could try:
return View(links.ToPagedList(pageNumber, pageSize, m => m.ID, true));
It's off the top of my head, so I'm sorry if it doesn't work perfectly...
-- Wow, just noticed the date on this one... I need to stop trawling the unanswered pages without sorting by date!
来源:https://stackoverflow.com/questions/8638787/topagedlist-order-differs-from-the-linq-order-by-clause