I have a ShoeItem class where I store a few Shoe attributes such as Model, Price, Color..
In the Index view of my ShoeController, I show the user a List of the shoes s/he requested using some filters, there is no problem here..
The list is shown in the default MVC 3.0 list view.. My @Model of the view page (“Index.cshtml”) is of type List<ShoeItem>
However, I want the user to be able to sort the resulting list according to those attributes both ascending or descending but I can not..
I tried calling a PartialViewResult from the ShoeController by sending back the List<ShoeItem> as parameter within Ajax.BeginForm, sort it back there and show a PartialView with this sorted list but the List parameter comes to the controller as null..
I also tried jQuery to do the sorting client-side but I could not reach the List<ShoeItem> object from jQuery.. I may post the code if you would like to see but it’s simple..
Any ideas?
There are 2 options
/shoes/?sort=model&dir=asc. Take these parameteres into the controller action, retrieve the items, sort them and return a JsonResult. Render the new list via JavaScript.The first method is harder to maintain as you end up rendering from 2 different places – server and client. Although this would be made easier by using some kind of templating library like moustache: https://github.com/janl/mustache.js.
For the second option you controller would look like the following. I’ve made some assumptions and it could probably be streamlined but helpfully it will get you started. If your shoes are stored in a database, make sure you do the filtering and ordering on an IQueryable – that way the database server will do it, rather than the data being returned to .NET, then filtering it.