I was wondering how people were going about sorting a table in asp.net mvc? I\'ve heard of javascript solutions that work pretty well with non-paged tables, such as jquery\'s ta
Definately liking Jan's solution - thanks a lot Jan... You just saved me some 60 lines of code with a case statement parsing each of the column headers. The solution "makes a great toggle click, only sort by 1 column solution on tables", when used with two session variables, one to retain the ASC/DESC as a boolean and one to hold the Type/Column Name.
I used this C# Example Extension and implemented it with VB this afternoon. I managed to cut a 30 line case statement into one line of code.
AT THE VIEW:
<th>Date <a class="clickable" href="<%=Url.Action("SortStationVisits", New With {.SortField = "PlanningDate"})%>"><span class="colSort" style="display: inline-table;"></span></a></th>
THE EXTENSION (Public Module OrderByExtender):
Imports System.Linq.Expressions
Public Function OrderBy(Of T)(collection As IEnumerable(Of T), key As String, isDescending As Boolean) As IOrderedEnumerable(Of T)
Dim sortLambda As LambdaExpression = BuildLambda(Of T)(key)
If isDescending Then
Return collection.OrderByDescending(DirectCast(sortLambda.Compile(), Func(Of T, Object)))
Else
Return collection.OrderBy(DirectCast(sortLambda.Compile(), Func(Of T, Object)))
End If
End Function
Public Function ThenBy(Of T)(collection As IOrderedEnumerable(Of T), key As String, isDescending As Boolean) As IOrderedEnumerable(Of T)
Dim sortLambda As LambdaExpression = BuildLambda(Of T)(key)
If (isDescending) Then
Return collection.ThenByDescending(DirectCast(sortLambda.Compile(), Func(Of T, Object)))
Else
Return collection.ThenBy(DirectCast(sortLambda.Compile(), Func(Of T, Object)))
End If
End Function
Private Function BuildLambda(Of T)(key As String) As LambdaExpression
Dim TParameterExpression As ParameterExpression = Expression.Parameter(GetType(T), "p")
Dim sortLambda As LambdaExpression = Expression.Lambda(Expression.Convert(Expression.[Property](TParameterExpression, key), GetType(Object)), TParameterExpression)
Return sortLambda
End Function
AT THE CONTROLLER ACTION:
Public Function SortStationVisits(Optional page As Integer = 1, Optional SortField As String = "") As ActionResult
Dim sps = LoadSession()
If SortField = sps.StationVisitSorter Then
sps.StationVisitDescOrder = Not (sps.StationVisitDescOrder)
Else
sps.StationVisitDescOrder = False
End If
sps.StationVisitSorter = SortField
SaveSession(sps)
Return RedirectToAction("Show")
End Function
AT THE CONTROLLER SHOW METHOD (1 line of code W00T!) :
spv.SelectableStationVisits = spv.SelectableStationVisits.OrderBy(sps.StationVisitSorter, sps.StationVisitDescOrder).ToList
I prefer the methods described here: http://www.c-sharpcorner.com/UploadFile/camurphy/csharpLists03302006170209PM/csharpLists.aspx
So for ex:
var products = new List<Products>();
products = ProductRepository.GetAll();
// Sort Results
products.Sort(
delegate(Products p1, Products p2) {
return p1.Name.CompareTo(p2.Name);
});
If JavaScript is disabled, you have a problem.
I'd go for a noscript solution.
I'd have two radio button groups:
direction: ( ) ascending (.) descending
orderBy: (.) Id ( ) Name ( ) Status
I'd treat the View as a form with multiple submit buttons:
(without JavaScript) ~~ same name for both buttons.
on your .aspx page, add three buttons:
<input type="submit" value="Requery" name="submitButton"/>
<input type="submit" value="Previous" name="submitButton"/>
<input type="submit" value="Next" name="submitButton"/>
in your Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Sort(string direction, string orderBy, string submitButton)
{
if (submitButton == "Requery") //et cetera
TMTOWTDI: There's More Than One Way To Do It
Try the following extension methods (from top of head):
static class OrderByExtender
{
public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> collection, string key, string direction)
{
LambdaExpression sortLambda = BuildLambda<T>(key);
if(direction.ToUpper() == "ASC")
return collection.OrderBy((Func<T, object>)sortLambda.Compile());
else
return collection.OrderByDescending((Func<T, object>)sortLambda.Compile());
}
public static IOrderedEnumerable<T> ThenBy<T>(this IOrderedEnumerable<T> collection, string key, string direction)
{
LambdaExpression sortLambda = BuildLambda<T>(key);
if (direction.ToUpper() == "ASC")
return collection.ThenBy((Func<T, object>)sortLambda.Compile());
else
return collection.ThenByDescending((Func<T, object>)sortLambda.Compile());
}
private static LambdaExpression BuildLambda<T>(string key)
{
ParameterExpression TParameterExpression = Expression.Parameter(typeof(T), "p");
LambdaExpression sortLambda = Expression.Lambda(Expression.Convert(Expression.Property(TParameterExpression, key), typeof(object)), TParameterExpression);
return sortLambda;
}
}
Usage:
var products = Session["Model"] as IEnumerable<Product>() ?? _service.GetAll();
return products.OrderBy("Name", "ASC").ThenBy("Price", "DESC");
Assuming you are only using 1 orderby condition at a time you can use:
var products = Session["Model"] as IEnumerable<Product>();
var sortDirection = Session["Direction"] as string ?? "DESC";
Session["Direction"] = sortDirection == "DESC" ? "ASC" : "DESC";
sortDirection = Session["Direction"] as string;
return products.OrderBy(parameter, sortDirection);
Check out the DataTables @ DataTables This will let you page the result and query it with easy setup. it works well with ajax and json data. Look at the samples. Hope this will help you out.