I'm writing an asp.net mvc app and I've get a list of service calls that I display in a table. When the user clicks the table header I want to tell my controller to sort the list by that column.
public ActionResult Index(int? page, string sortBy, string sortDirection)
{
int pageIndex = page == null ? 0 : (int)page - 1;
IServiceCallService scService = new ServiceCallService();
IPagedList<ServiceCall> serviceCalls = scService.GetOpenServiceCalls("").ToPagedList(pageIndex, 2);
return View("List", serviceCalls);
}
How do I incorporate the sortBy and sortDirection. I think I could do something like:
IPagedList<ServiceCall> serviceCalls = sc.Service.GetOpenServiceCalls("").OrderBy(sortBy).ToPagedList(pageIndex, 2);
But that doesn't work because I assume OrderBy wants a lambda like p => p.CreateDate but not sure how to do this.
I know ways I could do it but they are ugly and I'm sure C# has something simple here that I'm just missing.
Thanks.
-
When sorting a generic list, you can provide the way to compare for sorting with an overload of
List<T>.Sort():public void Sort( Comparison<T> comparison )Here is the example from MSDN. The
Comparison<T>comparison is a delegate that provides the method for comparing objects when sorting.I may be wrong, but I believe if your list includes only items of the same type and that type implements
IComparable, the delegate may not be necessary. -
Don't forget about the handy-dandy DataBinder:
var serviceCalls = sc.Service.GetOpenServiceCalls("").OrderBy(call => DataBinder.Eval(call, sortBy)); return serviceCalls.ToPagedList(pageIndex, 2);DataBinder.Eval from Msdn docs
Uses reflection to parse and evaluate a data-binding expression again an object at run time.
-
You could also use leverage jQuery and use something like Table Sorter if you're just looking to sort the list. It'd also be real time and all ajax-y.
0 comments:
Post a Comment