cihankus
cihankus

Reputation: 23

Sorting a List<T> object in MVC view page

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?

Upvotes: 1

Views: 5892

Answers (1)

Ian Routledge
Ian Routledge

Reputation: 4042

There are 2 options

  1. Make an AJAX request to the server passing the sort parameters e.g. /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.
  2. Make an AJAX/full page request to the server with the sort params. Take these parameteres into the controller action, retrieve the items and return a PartialView for AJAX and a ViewResult for full page request.

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.

public ViewResult Index(int? colour, string sort, string dir)
{
    IQueryable<Shoe> shoes = shoeService.GetAllShoes();

    // Filter by something
    if(colour.HasValue)
        shoes = shoes.Where(s => s.Colour = colour);

    // Order the items
    switch((sort ?? "").ToLower())
    {
        case "colour":
            if(dir == "desc")
                shoes = shoes.OrderByDescending(s => s.Colour.Name);
            else
                shoes = shoes.OrderBy(s => s.Colour.Name);
            break;
    }

    if(Request.IsAjaxRequest())
        return PartialView(shoes.ToList());
    return View(shoes.ToList());
}

Upvotes: 2

Related Questions