C# MVC layui table 前后端交互 (临时json文件读写,table列为object,反射)

该博客介绍了如何在C# MVC应用中使用临时Json文件存储和更新数据,以减少对数据库的频繁访问。同时,它详细展示了如何处理layuitable表格的分页、排序和搜索功能,包括反射操作对象属性以生成进度条。代码示例展示了如何读取和写入Json文件,以及如何根据用户输入进行数据过滤和排序。
摘要由CSDN通过智能技术生成

目录

项目场景:

问题描述:

原因分析:

解决方案:


项目场景:

C# MVC layui table 前后端交互 (临时json文件读写,table列为object,反射)



问题描述:

1.后端代码生成临时json文件,从而达到定时更新数据,不用频繁访问数据库,适用于不用实时获取数据;

2.当layui table的列为object(如list)时,对此object对象属性进行操作(如生成进度条)

3.通过反射进行对象属性处理



解决方案:

代码如下:

/// <summary>
        /// 读取临文件,若存在就读取,不存在则生成临时文件
        /// </summary>
        /// <returns></returns>
        public List<ContractInspect> readFile()
        {
            bool mark = false;
            List<ContractInspect> contractInspects = new List<ContractInspect>();
            DirectoryInfo infos = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/File/TestProgress/TempFile.json"));
            var pp = infos.Parent.FullName;if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/File/TestProgress/TempFile.json")))
            {
                DateTime dateTime = System.IO.File.GetLastWriteTime(System.Web.HttpContext.Current.Server.MapPath("~/File/TestProgress/TempFile.json"));
                if (DateTime.Now > dateTime.AddHours(2))
                {
                    mark = true;
                }
                else
                {
                    StringBuilder resultJson = new StringBuilder();
                    using (StreamReader reader = System.IO.File.OpenText(pp.ToString() + @"/TempFile.json"))
                    {
                        resultJson.Append(reader.ReadToEnd());
                    }
                    contractInspects = JsonConvert.DeserializeObject<List<ContractInspect>>(resultJson.ToString());
                }
            }
            else
            {
                mark = true;
            }
            if (mark)
            {
                List<TestProgressModels> testProgressModels = testSummary_Complete();
                List<TestProgressModels> testProgressSingle = testProgressModels.Distinct(a => a.projectNum).ToList();
                List<int> contractid = contrantid();
                List<ContractModel> contractModel = contract(contractid);
                List<ContractInspectionModel> contractInspectionModel = contractInspection(contractid);contractInspects = (from a in contractModel
                                    join b in testProgressSingle on a.projectNum equals b.projectNum
                                    join c in contractInspectionModel on a.contractID equals c.contractID
                                    select new ContractInspect
                                    {
                                        contractID = a.contractID,
                                        fatherID = c.fatherID,
                                        projectName = b.projectName,
                                        projectNum = b.projectNum,
                                        inspectionName = c.inspectionName,
                                        statusName = c.statusName
                                    }).ToList();
                int Count = contractInspects.Count();
                IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
                timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                string enddata = JsonConvert.SerializeObject(contractInspects, timeConverter);
                //string json = "{\"code\":0,\"msg\":\"" + DateTime.Now + "\",\"count\":" + Count + ",\"data\":" + enddata + "}";
                System.IO.File.WriteAllText(pp.ToString() + @"/TempFile.json", enddata);
            }
            return contractInspects;
        }
/// <summary>
        /// 读取附件数据,生成前端table显示数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public ContentResult tableResult(int page = 1, int limit = 10) 
        {
            List<ContractInspect> contractInspects = new List<ContractInspect>();
            contractInspects = readFile();
            List<OutData> outData = (from a in contractInspects
                                     group a by new { a.contractID, a.projectName,a.projectNum,a.contractNumber} into g
                                     select new OutData
                                     {
                                         projectNum=g.Key.projectNum,
                                         contractID = g.Key.contractID,
                                         contractNumber = g.Key.contractNumber,
                                         projectName = g.Key.projectName,
                                         total = g.Count(a => a.fatherID != 0),
                                         part = g.Count(a => a.statusName == "录入完毕" && a.fatherID != 0),
                                         percent = (double)g.Count(a => a.statusName == "录入完毕" && a.fatherID != 0) / (g.Count(a => a.fatherID != 0) == 0 ? 1 : g.Count(a => a.fatherID != 0))
                                     }).OrderByDescending(a => a.contractID).ToList();
            List<OutData> totalData = new List<OutData>();
            foreach (var item in outData){
                OutData outData1 = new OutData() { mathDatas = new MathDatas() };
                MathDatas mathDatas = new MathDatas();
                mathDatas = outData.Where(a => a.contractID.Equals(item.contractID)).Select(a => new MathDatas { part = a.part, percent = a.percent, total = a.total }).FirstOrDefault();
                outData1.mathDatas = mathDatas;
                outData1.contractID = item.contractID;
                outData1.projectNum = item.projectNum;
                outData1.projectName = item.projectName;
                outData1.contractNumber = item.contractNumber;
                totalData.Add(outData1);
            }
            string end = JsonConvert.SerializeObject(totalData);
            DirectoryInfo info = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/File/TestProgress/TempOutFile.json"));
            var p = info.Parent.FullName;
            System.IO.File.WriteAllText(p.ToString() + @"/TempOutFile.json", end);
            int count = totalData.Count();
            if (count > 0)
            {

                if ((page - 1) * limit > count)
                {
                    page = 1;
                }
                totalData = totalData.Skip((page - 1) * limit).Take(limit).ToList();
            }                   
            IsoDateTimeConverter timeConverter1 = new IsoDateTimeConverter();
            timeConverter1.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            string end1 = JsonConvert.SerializeObject(totalData, timeConverter1);
            string json = "{\"code\":0,\"msg\":\"\",\"count\":" + count + ",\"data\":" + end1 + "}";
            return Content(json, "application/json");
        }
/// <summary>
        /// 对于table分页、排序、搜索功能
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="field"></param>
        /// <param name="order"></param>
        /// <param name="SearchText"></param>
        /// <param name="Rateslt"></param>
        /// <returns></returns>
        public ContentResult TableData(int page = 1, int limit = 10, string field = "", string order = "", string SearchText = "", string Rateslt = "")
        {
            List<OutData> outDatas = new List<OutData>();
            DirectoryInfo infos = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/File/TestProgress/TempOutFile.json"));
            var pp = infos.Parent.FullName;
            StringBuilder resultJson = new StringBuilder();
            using (StreamReader reader = System.IO.File.OpenText(pp.ToString() + @"/TempOutFile.json"))
            {
                resultJson.Append(reader.ReadToEnd());
            }
            outDatas = JsonConvert.DeserializeObject<List<OutData>>(resultJson.ToString());
            if (SearchText!="")
            {
                outDatas = outDatas.Where(a => a.projectNum.Contains(SearchText)).ToList();
            }
            if (Rateslt != "")
            {
                outDatas = outDatas.Where(a => ((MathDatas)typeof(OutData).GetProperty("mathDatas").GetValue(a)).percent>=Convert.ToDouble(Rateslt)/100).ToList();
            }
            switch (order)
            {
                case "desc":
                        outDatas =outDatas.Where(a=>a.mathDatas!=null).OrderByDescending(s => ((MathDatas)typeof(OutData).GetProperty(field).GetValue(s)).percent).ToList();                  
                    break;
                case "asc":
                    outDatas = outDatas.OrderBy(s => ((MathDatas)typeof(OutData).GetProperty(field).GetValue(s)).percent).ToList();
                    break;
                default:
                    break;
            }
            int Count = outDatas.Count();
            if (Count > 0)
            {

                if ((page - 1) * limit > Count)
                {
                    page = 1;
                }
                outDatas = outDatas.Skip((page - 1) * limit).Take(limit).ToList();

            }
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            string enddata = JsonConvert.SerializeObject(outDatas, timeConverter);
            string json = "{\"code\":0,\"msg\":\"\",\"count\":" + Count + ",\"data\":" + enddata + "}";
            return Content(json, "application/json");
        }
<script type="text/html" id="mathDatas">
        <!-- 这里的 checked 的状态只是演示 -->
        {{# if(d.mathDatas.total != ""){ }}
        <div class="layui-row">
            <div class="layui-col-xs11 layui-col-sm11 layui-col-md11 layui-progress layui-progress-big" style="top:4px;" lay-showpercent="true">
                <div class="layui-progress-bar" lay-percent="{{ (parseFloat(d.mathDatas.percent)*100).toFixed(1)  }}%"></div>
            </div>
            <div class="layui-col-xs1 layui-col-sm1 layui-col-md1" style="left:2px;">{{d.mathDatas.part}}/{{d.mathDatas.total}}</div>
        </div>
        {{# } }}

    </script>
    <div id="">
        <script type="text/html" id="toolbarDemo1">
            <div class="">
                <div class="layui-inline">
                    <input class="layui-input" style="height:38px" name="" id="alldes" placeholder="根据单号检索" autocomplete="off">
                </div>
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <input class="layui-input" type="number" style="height:38px" name="" id="rateslt" placeholder="完成率" autocomplete="off">
                    </div>
                    %
                </div>
                <div class="layui-inline layui-btn-container">
                    <button id="selectReload" class="layui-btn layui-btn-sm" lay-event="reload">搜索</button>
                </div>
            </div>
        </script>
<script>    
    layui.use(['table', 'element'], function () {
        var table = layui.table;
        var element = layui.element;
        $(document).ready(function () {
            ProgressFun();
        });
        function ProgressFun() {
            table.render({
                elem: '#table_Progress'
                , url: '/TestProgress/tableResult'
                , page: true //开启分页
                , id: 'progressTable'
                , autoSort: false
                , toolbar: '#toolbarDemo1' //开启头部工具栏,并为其绑定左侧模板
                , defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
                    title: '提示'
                    , layEvent: 'LAYTABLE_TIPS'
                    , icon: 'layui-icon-tips'
                }]
                , cols: [[
                    { field: 'contractNumber', title: '申请单号', event: 'ProjNumEvent', style: 'color:#359f6a', width: '12%' }
                    ,{ field: 'projectNum', title: '项目编号',  width: '10%' }
                    , { field: 'projectName', title: '项目名称', width: '30%' }
                    , { field: 'mathDatas', title: '项目当前进度', width: '48%', sort: true, templet: '#mathDatas' }
                ]]
                , page: {
                    theme: '#359f6a',
                    layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
                    , first: false
                    , last: false
                }
                , limit: 20
                , limits: [10, 20, 50, 100]
                , done: function () {

                    element.render()
                }
            });    
        }//监听排序事件 
        table.on('sort(TabevenTest)', function (obj) { //注:sort 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
            console.log(obj.field); //当前排序的字段名
            console.log(obj.type); //当前排序类型:desc(降序)、asc(升序)、null(空对象,默认排序)
            console.log(this);//当前排序的 th 对象
            console.log(obj);
            //尽管我们的 table 自带排序功能,但并没有请求服务端。
            //有些时候,你可能需要根据当前排序的字段,重新向服务端发送请求,从而实现服务端排序,如:
            var projectNum = $("#alldes")[0].value;
            var rateslt = $("#rateslt")[0].value;
            table.reload('progressTable', {
                url: '/TestProgress/TableData',
                initSort: obj //记录初始排序,如果不设的话,将无法标记表头的排序状态。
                , where: { //请求参数(注意:这里面的参数可任意定义,并非下面固定的格式)
                    field: obj.field //排序字段
                    , order: obj.type //排序方式
                    , SearchText: projectNum
                    , Rateslt: rateslt
                }
            });
            $("#alldes").val(projectNum);
            $("#rateslt").val(rateslt);
            // layer.msg('服务端排序。order by ' + obj.field + ' ' + obj.type);
        });
        table.on('toolbar(TabevenTest)', function (obj) { //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
            var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
            if (layEvent === 'reload') {
                var projectNum = $("#alldes")[0].value;
                var rateslt = $("#rateslt")[0].value;
                var send = {
                    projectNum: projectNum,
                    rateslt: rateslt,
                }
                ProjNumPage(send);
                $("#alldes").val(projectNum);
                $("#rateslt").val(rateslt);
            }              
        });table.on('tool(TabevenTest)', function (obj) { //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
            var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
            if (layEvent === 'ProjNumEvent') {
                var data = obj.data; //获得当前行数据
                var kk = data['contractNumber'];  //获取属性uid的值
                WindPage(kk);
            }
        });
        function ProjNumPage(send) {
            table.reload('progressTable', {
                url: '/TestProgress/TableData'
                , where: {
                    SearchText: send.projectNum
                    , Rateslt: send.rateslt
                }
            });
        }
        function WindPage(res) {
            layer.open({
                type: 2,// 2为iframe
                title: 'Edit',// 去掉标题
                shade: 0.1,//遮蔽
                shadeClose: false, //点击遮罩关闭
                maxmin: false, //最大化最小化按钮
                closeBtn: true, scrollbar: false,
                title: false,//标题栏不可见
                area: ['70%', '80%'],//
                anim: 5,// 渐变出现
                content: '/TestProgress/WindPage?contractNumber=' + res,// iframe链接地址
                id: 'name1',
                success: function (layero, index) {    //成功获得加载changefile.html时,预先加载,将值从父窗口传到 子窗口
              //      var body = layer.getChildFrame('body', index);//少了这个是不能从父页面向子页面传值的
              获取子页面的元素,进行数据渲染
              //      body.contents().find("#test").val(res);
                },
                yes: function (index, layero) {
                }
            });
        }
    });
        

</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值