ASP.NET MVC. Clean way to implement persistant sorting?
-
22-08-2019 - |
Question
I still haven`t found any example of sorting implementation through paging in ASP.NET MVC
(sort by name->press page 2->page 2 is still sorted by name).
I could "hack" it, make it dirty, but i`m sure there have to be good "how-to" guides for this.
What about sorting by two columns?
Solution
Just keep the sort expression in your model view and write it to the pagination route links.
For example like:
/MyEntity/Page/2?sort=Name
Or with custom routing like:
/MyEntity/Page/2/Name
For the latter the route mapping would look like:
{controller}/Page/{pageIndex}/{sortExpression}
OTHER TIPS
I do it exactly the way aleris does except I use a enum field on my model for the sort values, this way it will fall back on the default if they enter a sort paremeter that doesn't exist.
public enum SortArticle
{
Title,
Published
}
public enum SortOrder
{
Asc,
Desc
}
articles/{sort}/{order}/{page}
articles/published/desc/1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow