There are 2 things you need to do to get this right.
- Keep the sorting state is viewstate(SortDirection and SortExpression)
- You generate the correct linq expression based on the current sorting state.
Manually handle the Sorting event in the grid and use this helper I wrote to sort by SortExpression and SortDirection:
public static IQueryable<T> SortBy<T>(IQueryable<T> source, string sortExpression, SortDirection direction) {
if (source == null) {
throw new ArgumentNullException("source");
}
string methodName = "OrderBy";
if (direction == SortDirection.Descending) {
methodName += "Descending";
}
var paramExp = Expression.Parameter(typeof(T), String.Empty);
var propExp = Expression.PropertyOrField(paramExp, sortExpression);
// p => p.sortExpression
var sortLambda = Expression.Lambda(propExp, paramExp);
var methodCallExp = Expression.Call(
typeof(Queryable),
methodName,
new[] { typeof(T), propExp.Type },
source.Expression,
Expression.Quote(sortLambda)
);
return (IQueryable<T>)source.Provider.CreateQuery(methodCallExp);
}
db.Products.SortBy(e.SortExpression, e.SortDirection)
Check out my blog post on how to do this:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…