Sorting a table in asp.net MVC

前端 未结 5 1271
半阙折子戏
半阙折子戏 2021-02-07 08:36

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

5条回答
  •  广开言路
    2021-02-07 09:09

    Try the following extension methods (from top of head):

    static class OrderByExtender
    {
        public static IOrderedEnumerable OrderBy(this IEnumerable collection, string key, string direction)
        {
            LambdaExpression sortLambda = BuildLambda(key);
    
            if(direction.ToUpper() == "ASC")
                return collection.OrderBy((Func)sortLambda.Compile());
            else
                return collection.OrderByDescending((Func)sortLambda.Compile());
        }
    
        public static IOrderedEnumerable ThenBy(this IOrderedEnumerable collection, string key, string direction)
        {
            LambdaExpression sortLambda = BuildLambda(key);
    
            if (direction.ToUpper() == "ASC")
                return collection.ThenBy((Func)sortLambda.Compile());
            else
                return collection.ThenByDescending((Func)sortLambda.Compile());
        }
    
        private static LambdaExpression BuildLambda(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() ?? _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();
    
    var sortDirection = Session["Direction"] as string ?? "DESC";
    Session["Direction"] = sortDirection == "DESC" ? "ASC" : "DESC";
    sortDirection = Session["Direction"] as string;
    
    return products.OrderBy(parameter, sortDirection);
    

提交回复
热议问题