• easyui datagrid remoteSort的实现 Controllers编写动态的Lambda表达式 IQueryable OrderBy扩展


    • EF 结合easy-ui datagrid 实现页面端排序
    • EF动态编写排序Lambda表达式

    1、前端页面

     var mainListHeight = $(window).height() - 20;
            $(document).ready(function () {
                $("#AppLogGrid").datagrid({
                    "title": "应用程序日志记录",
                    "iconCls": "icon-blank",
                    "width": "100%",
                    "height": mainListHeight,
                    "nowrap": false,
                    "striped": true,
                    "pagination": true,
                    "rownumbers": true,
                    "remoteSort": true,
                    "pageList": [50, 100, 200, 500, 1000],
                    "frozenColumns": [[
                     { "field": "ck", checkbox: true }
                 ]],
                    "toolbar": "#tb",
                    "columns": [[
                    { "field": "nId", "title": "序号", "width": 60, "align": "right", "sortable": true },
                    { "field": "dtDate", "title": "日志记录时间", "width": 120, "align": "center", "sortable": true },
                    { "field": "sLevel", "title": "日志等级", "width": 80, "align": "center", "sortable": true },
                    { "field": "sLogger", "title": "Logger类", "width": 80, "align": "left" },
                    { "field": "sMessage", "title": "日志内容", "width": 660, "align": "left" }
                ]]
                })
                //初始化
                loadGrid();
            });
            //刷新表格
            function loadGrid() {
                var p = {
                    "url": "/CommonBiz/GetAppLogList",
                    "data": {
                        "Parameter": {
                            "LogLevel": $("#logLevel").val()
                        }
                    }
                }
                $("#AppLogGrid").datagrid({ "url": p.url, "queryParams": { "Parameter": $.toJSON(p.data)} });
            }
    

    设置了“dtDate”和“sLevel” 两个字段允许( "remoteSort": true)在页面排序。

    2、后端Controller代码

    /// <summary>
            /// 获取某类型日志记录
            /// </summary>
            /// <returns></returns>
            public JsonResult GetAppLogList()
            {
                using (Reserve_DbEntities db = new Reserve_DbEntities())
                {
                    var list = new List<AppSystemLog>();
                    string queryParams = Request.Form["Parameter"];
                    int pageRowNum = int.Parse(Request.Form["rows"]);
                    int pageIndex = int.Parse(Request.Form["page"]);
                    string sortField = Request.Form["sort"] as string;
                    string order = Request.Form["order"] as string;
                    if (!string.IsNullOrEmpty(queryParams))
                    {
                        var resultJson = JObject.Parse(queryParams);
                        string level = resultJson["Parameter"]["LogLevel"].Value<string>();
                        if (string.IsNullOrEmpty(sortField))
                        {
                            if (level.Equals("ALL"))
                                list = db.AppSystemLog.OrderByDescending(l => l.nId).ToList();
                            else list = db.AppSystemLog.Where(l => l.sLevel == level).OrderByDescending(o => o.dtDate).ToList();
                        }
                        else
                        {
                            if (level.Equals("ALL"))
                                list = db.AppSystemLog.OrderBy<AppSystemLog>(sortField, order.Equals("asc") ? true : false).ToList();
                            else list = db.AppSystemLog.Where(l => l.sLevel == level).OrderBy<AppSystemLog>(sortField, order.Equals("asc") ? true : false).ToList();
                        }
                    }
                    var resultRows = list.Skip((pageIndex - 1) * pageRowNum).Take(pageRowNum).ToList();
                    var jsonResult = new { total = list.Count, rows = resultRows };
                    return Json(jsonResult, JsonRequestBehavior.AllowGet);
                }
            }
    

    这里的技巧是需要扩展IQueryable,因为一般写法是 list.OrderBy(o=>o.XXXX字段“显示的写法”)。而页面post过来的字段名称是会变的,这样后端必须实现动态编写Lambda表达式,一翻搜索发现扩展的方法:

    /// <summary>
        /// IQueryable扩展
        /// </summary>
        public static class QueryableExter
        {
            public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName, bool ascending) where T : class
            {
                Type type = typeof(T);
                PropertyInfo property = type.GetProperty(propertyName);
                if (property == null)
                    throw new ArgumentException("propertyName", "Not Exist");
                ParameterExpression param = Expression.Parameter(type, "p");
                Expression propertyAccessExpression = Expression.MakeMemberAccess(param, property);
                LambdaExpression orderByExpression = Expression.Lambda(propertyAccessExpression, param);
                string methodName = ascending ? "OrderBy" : "OrderByDescending";
                MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName, new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExpression));
    
                return source.Provider.CreateQuery<T>(resultExp);
            }
        }
    

    3、截图show

      

  • 相关阅读:
    [leetcode]34.Find First and Last Position of Element in Sorted Array找区间
    [leetcode]278. First Bad Version首个坏版本
    [leetcode]367. Valid Perfect Square验证完全平方数
    [leetcode]45. Jump Game II青蛙跳(跳到终点最小步数)
    [leetcode]55. Jump Game青蛙跳(能否跳到终点)
    [leetcode]26. Remove Duplicates from Sorted Array有序数组去重(单个元素只出现一次)
    [leetcode]27. Remove Element删除元素
    [leetcode]20. Valid Parentheses有效括号序列
    [leetcode]15. 3Sum三数之和
    C#中的局部类型
  • 原文地址:https://www.cnblogs.com/datacool/p/easyui-datagrid-sort-lamuda.html
Copyright © 2020-2023  润新知