zoukankan      html  css  js  c++  java
  • c# 行转列动态赋值给layui

    数据库存储格式

    期望前端显示样式

    以下是代码:

    (1)控制器:

            [HttpGet("SocialImportLedgerInfo")]
            public ResultData GetSocialImportLedgerInfo()
            {
                ResultData result = new ResultData();
                string json = socialHandler.RowsToColumn();
                if (json != null)
                {
                    result.Data = json;
                    result.Code = 200;
                    result.Msg = "成功";
                }
                else
                {
                    result.Data = null;
                    result.Code = 500;
                    result.Msg = "无数据";
                }
    
                return result;
            }

    (2)逻辑层数据处理

           public string RowsToColumn()
            {
                string json = JsonConvert.SerializeObject(socialRepositories.RowsToColumn(), new KeyValuePairConverter());
                return json;
            }

     (3)仓储层数据源

            public object[] RowsToColumn()
            {
                var SocialImportLedgerInfo = (from b in db.SocialImportLedger
                                       where b.IsPaymentBill == 0
                                       select new
                                       {
                                           Name = b.Name,
                                           Value = b.Value,
                                           EmlpoyeeId = b.EmlpoyeeId
                                       }).ToArray();
    
                if (SocialImportLedgerInfo.Length > 0)
                {
                    return SocialImportLedgerInfo.ToPivotArray(i => i.Name, i => i.EmlpoyeeId, items => items.Any() ? items.FirstOrDefault().Value : null);
                }
                else
                {
                    return null;
                }
            }
        }

    (4)行转列方法:ToPivotArray

       public static class RowToColumnHelper
        {
            public static dynamic[] ToPivotArray<T, TColumn, TRow, TData>(this IEnumerable<T> source, Func<T, TColumn> columnSelector, Expression<Func<T, TRow>> rowSelector, Func<IEnumerable<T>, TData> dataSelector)
            {
                var arr = new List<object>();
                var cols = new List<string>();
                string rowName = ((MemberExpression)rowSelector.Body).Member.Name;
                var columns = source.Select(columnSelector).Distinct();
    
                cols = (new[] { rowName }).Concat(columns.Select(x => x.ToString())).ToList();
    
                var rows = source.GroupBy(rowSelector.Compile())
                                 .Select(rowGroup => new
                                 {
                                     Key = rowGroup.Key,
                                     Values = columns.GroupJoin(
                                         rowGroup,
                                         c => c,
                                         r => columnSelector(r),
                                         (c, columnGroup) => dataSelector(columnGroup))
                                 }).ToArray();
    
                foreach (var row in rows)
                {
                    var items = row.Values.Cast<object>().ToList();
                    items.Insert(0, row.Key);
                    var obj = GetAnonymousObject(cols, items);
                    arr.Add(obj);
                }
    
                return arr.ToArray();
            }
    
            private static dynamic GetAnonymousObject(IEnumerable<string> columns, IEnumerable<object> values)
            {
                IDictionary<string, object> eo = new ExpandoObject() as IDictionary<string, object>;
                int i;
                for (i = 0; i < columns.Count(); i++)
                {
                    eo.Add(columns.ElementAt(i), values.ElementAt(i));
                }
    
                return eo;
            }
        }

    (5)前端layui接收

    @{
        ViewData["Title"] = "SocialSettlementPayment";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <div class="layui-container">
        <script type="text/html" id="barDemo">
            <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>
            <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        </script>
    
        <table class="layui-hide" id="socialList" lay-filter="socialList"></table>
    </div>
    <script>
        var a;
        $.ajax({
            url: '/Social/SocialImportLedgerInfo',
            type: 'get',
            dataType: "json",
            success: function (result) {
                var b = JSON.parse(result.data);
                console.log(b);
    
                datalist = [{ checkbox: true, fixed: "left",  40, templet: '#indexTpl' }];
    
                $.each(b[0], function (name, value) {
                    console.log(name);
                    var f = {};
                    f.field = name;
                    f.title = name;
                    f.width = 250;
                    datalist.push(f);
                });
                console.log(datalist);
    
                layui.use('table', function () {
                    var table = layui.table;
    
                    //展示已知数据
                    table.render({
                        elem: '#socialList'
                        , cols: [datalist]
                        , data: b
                        , even: true
                        , page: true //是否显示分页
                        , toolbar: 'default' //开启工具栏,此处显示默认图标,可以自定义模板,详见文档
                        ,limits: [10, 20, 50, 100, 500, 1000]
                        ,limit: 10 //每页默认显示的数量
                    });
    
                    //监听头工具栏事件
                    table.on('toolbar(test)', function (obj) {
                        var checkStatus = table.checkStatus(obj.config.id)
                            , data = checkStatus.data; //获取选中的数据
                        switch (obj.event) {
                            case 'add':
                                layer.msg('添加');
                                break;
                            case 'update':
                                if (data.length === 0) {
                                    layer.msg('请选择一行');
                                } else if (data.length > 1) {
                                    layer.msg('只能同时编辑一个');
                                } else {
                                    layer.alert('编辑 [id]:' + checkStatus.data[0].id);
                                }
                                break;
                            case 'delete':
                                if (data.length === 0) {
                                    layer.msg('请选择一行');
                                } else {
                                    layer.msg('删除');
                                }
                                break;
                        };
                    });
    
                    //监听行工具事件
                    table.on('tool(test)', function (obj) { //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
                        var data = obj.data //获得当前行数据
                            , layEvent = obj.event; //获得 lay-event 对应的值
                        if (layEvent === 'detail') {
                            layer.msg('查看操作');
                        } else if (layEvent === 'del') {
                            layer.confirm('真的删除行么', function (index) {
                                obj.del(); //删除对应行(tr)的DOM结构
                                layer.close(index);
                                //向服务端发送删除指令
                            });
                        } else if (layEvent === 'edit') {
                            layer.msg('编辑操作');
                        }
                    });
                });
            }
        });
    </script>
  • 相关阅读:
    esp32(M5STACK)在线体验(Ubuntu)
    esp32(M5STACK)程序烧写(Ubuntu)
    在Ubuntu环境下搭建esp32开发环境
    markdown让文字居中和带颜色
    Doxyfile中插入图片
    System.load 与 System.loadLibrary 的使用
    常见mysql的数据迁移
    mysql中有关树的函数
    spring整合quartz实现动态定时器
    javaweb项目中发布webservices服务
  • 原文地址:https://www.cnblogs.com/yxcn/p/9815660.html
Copyright © 2011-2022 走看看