当前位置:   article > 正文

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

前端layui后端c#

目录

项目场景:

问题描述:

原因分析:

解决方案:


项目场景:

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



问题描述:

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

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

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



解决方案:

代码如下:

  1. /// <summary>
  2. /// 读取临文件,若存在就读取,不存在则生成临时文件
  3. /// </summary>
  4. /// <returns></returns>
  5. public List<ContractInspect> readFile()
  6. {
  7. bool mark = false;
  8. List<ContractInspect> contractInspects = new List<ContractInspect>();
  9. DirectoryInfo infos = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/File/TestProgress/TempFile.json"));
  10. var pp = infos.Parent.FullName;if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/File/TestProgress/TempFile.json")))
  11. {
  12. DateTime dateTime = System.IO.File.GetLastWriteTime(System.Web.HttpContext.Current.Server.MapPath("~/File/TestProgress/TempFile.json"));
  13. if (DateTime.Now > dateTime.AddHours(2))
  14. {
  15. mark = true;
  16. }
  17. else
  18. {
  19. StringBuilder resultJson = new StringBuilder();
  20. using (StreamReader reader = System.IO.File.OpenText(pp.ToString() + @"/TempFile.json"))
  21. {
  22. resultJson.Append(reader.ReadToEnd());
  23. }
  24. contractInspects = JsonConvert.DeserializeObject<List<ContractInspect>>(resultJson.ToString());
  25. }
  26. }
  27. else
  28. {
  29. mark = true;
  30. }
  31. if (mark)
  32. {
  33. List<TestProgressModels> testProgressModels = testSummary_Complete();
  34. List<TestProgressModels> testProgressSingle = testProgressModels.Distinct(a => a.projectNum).ToList();
  35. List<int> contractid = contrantid();
  36. List<ContractModel> contractModel = contract(contractid);
  37. List<ContractInspectionModel> contractInspectionModel = contractInspection(contractid);contractInspects = (from a in contractModel
  38. join b in testProgressSingle on a.projectNum equals b.projectNum
  39. join c in contractInspectionModel on a.contractID equals c.contractID
  40. select new ContractInspect
  41. {
  42. contractID = a.contractID,
  43. fatherID = c.fatherID,
  44. projectName = b.projectName,
  45. projectNum = b.projectNum,
  46. inspectionName = c.inspectionName,
  47. statusName = c.statusName
  48. }).ToList();
  49. int Count = contractInspects.Count();
  50. IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
  51. timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
  52. string enddata = JsonConvert.SerializeObject(contractInspects, timeConverter);
  53. //string json = "{\"code\":0,\"msg\":\"" + DateTime.Now + "\",\"count\":" + Count + ",\"data\":" + enddata + "}";
  54. System.IO.File.WriteAllText(pp.ToString() + @"/TempFile.json", enddata);
  55. }
  56. return contractInspects;
  57. }
  1. /// <summary>
  2. /// 读取附件数据,生成前端table显示数据
  3. /// </summary>
  4. /// <param name="page"></param>
  5. /// <param name="limit"></param>
  6. /// <returns></returns>
  7. public ContentResult tableResult(int page = 1, int limit = 10)
  8. {
  9. List<ContractInspect> contractInspects = new List<ContractInspect>();
  10. contractInspects = readFile();
  11. List<OutData> outData = (from a in contractInspects
  12. group a by new { a.contractID, a.projectName,a.projectNum,a.contractNumber} into g
  13. select new OutData
  14. {
  15. projectNum=g.Key.projectNum,
  16. contractID = g.Key.contractID,
  17. contractNumber = g.Key.contractNumber,
  18. projectName = g.Key.projectName,
  19. total = g.Count(a => a.fatherID != 0),
  20. part = g.Count(a => a.statusName == "录入完毕" && a.fatherID != 0),
  21. percent = (double)g.Count(a => a.statusName == "录入完毕" && a.fatherID != 0) / (g.Count(a => a.fatherID != 0) == 0 ? 1 : g.Count(a => a.fatherID != 0))
  22. }).OrderByDescending(a => a.contractID).ToList();
  23. List<OutData> totalData = new List<OutData>();
  24. foreach (var item in outData){
  25. OutData outData1 = new OutData() { mathDatas = new MathDatas() };
  26. MathDatas mathDatas = new MathDatas();
  27. mathDatas = outData.Where(a => a.contractID.Equals(item.contractID)).Select(a => new MathDatas { part = a.part, percent = a.percent, total = a.total }).FirstOrDefault();
  28. outData1.mathDatas = mathDatas;
  29. outData1.contractID = item.contractID;
  30. outData1.projectNum = item.projectNum;
  31. outData1.projectName = item.projectName;
  32. outData1.contractNumber = item.contractNumber;
  33. totalData.Add(outData1);
  34. }
  35. string end = JsonConvert.SerializeObject(totalData);
  36. DirectoryInfo info = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/File/TestProgress/TempOutFile.json"));
  37. var p = info.Parent.FullName;
  38. System.IO.File.WriteAllText(p.ToString() + @"/TempOutFile.json", end);
  39. int count = totalData.Count();
  40. if (count > 0)
  41. {
  42. if ((page - 1) * limit > count)
  43. {
  44. page = 1;
  45. }
  46. totalData = totalData.Skip((page - 1) * limit).Take(limit).ToList();
  47. }
  48. IsoDateTimeConverter timeConverter1 = new IsoDateTimeConverter();
  49. timeConverter1.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
  50. string end1 = JsonConvert.SerializeObject(totalData, timeConverter1);
  51. string json = "{\"code\":0,\"msg\":\"\",\"count\":" + count + ",\"data\":" + end1 + "}";
  52. return Content(json, "application/json");
  53. }
  1. /// <summary>
  2. /// 对于table分页、排序、搜索功能
  3. /// </summary>
  4. /// <param name="page"></param>
  5. /// <param name="limit"></param>
  6. /// <param name="field"></param>
  7. /// <param name="order"></param>
  8. /// <param name="SearchText"></param>
  9. /// <param name="Rateslt"></param>
  10. /// <returns></returns>
  11. public ContentResult TableData(int page = 1, int limit = 10, string field = "", string order = "", string SearchText = "", string Rateslt = "")
  12. {
  13. List<OutData> outDatas = new List<OutData>();
  14. DirectoryInfo infos = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/File/TestProgress/TempOutFile.json"));
  15. var pp = infos.Parent.FullName;
  16. StringBuilder resultJson = new StringBuilder();
  17. using (StreamReader reader = System.IO.File.OpenText(pp.ToString() + @"/TempOutFile.json"))
  18. {
  19. resultJson.Append(reader.ReadToEnd());
  20. }
  21. outDatas = JsonConvert.DeserializeObject<List<OutData>>(resultJson.ToString());
  22. if (SearchText!="")
  23. {
  24. outDatas = outDatas.Where(a => a.projectNum.Contains(SearchText)).ToList();
  25. }
  26. if (Rateslt != "")
  27. {
  28. outDatas = outDatas.Where(a => ((MathDatas)typeof(OutData).GetProperty("mathDatas").GetValue(a)).percent>=Convert.ToDouble(Rateslt)/100).ToList();
  29. }
  30. switch (order)
  31. {
  32. case "desc":
  33. outDatas =outDatas.Where(a=>a.mathDatas!=null).OrderByDescending(s => ((MathDatas)typeof(OutData).GetProperty(field).GetValue(s)).percent).ToList();
  34. break;
  35. case "asc":
  36. outDatas = outDatas.OrderBy(s => ((MathDatas)typeof(OutData).GetProperty(field).GetValue(s)).percent).ToList();
  37. break;
  38. default:
  39. break;
  40. }
  41. int Count = outDatas.Count();
  42. if (Count > 0)
  43. {
  44. if ((page - 1) * limit > Count)
  45. {
  46. page = 1;
  47. }
  48. outDatas = outDatas.Skip((page - 1) * limit).Take(limit).ToList();
  49. }
  50. IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
  51. timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
  52. string enddata = JsonConvert.SerializeObject(outDatas, timeConverter);
  53. string json = "{\"code\":0,\"msg\":\"\",\"count\":" + Count + ",\"data\":" + enddata + "}";
  54. return Content(json, "application/json");
  55. }
  1. <script type="text/html" id="mathDatas">
  2. <!-- 这里的 checked 的状态只是演示 -->
  3. {{# if(d.mathDatas.total != ""){ }}
  4. <div class="layui-row">
  5. <div class="layui-col-xs11 layui-col-sm11 layui-col-md11 layui-progress layui-progress-big" style="top:4px;" lay-showpercent="true">
  6. <div class="layui-progress-bar" lay-percent="{{ (parseFloat(d.mathDatas.percent)*100).toFixed(1) }}%"></div>
  7. </div>
  8. <div class="layui-col-xs1 layui-col-sm1 layui-col-md1" style="left:2px;">{{d.mathDatas.part}}/{{d.mathDatas.total}}</div>
  9. </div>
  10. {{# } }}
  11. </script>
  12. <div id="">
  13. <script type="text/html" id="toolbarDemo1">
  14. <div class="">
  15. <div class="layui-inline">
  16. <input class="layui-input" style="height:38px" name="" id="alldes" placeholder="根据单号检索" autocomplete="off">
  17. </div>
  18. <div class="layui-inline">
  19. <div class="layui-input-inline">
  20. <input class="layui-input" type="number" style="height:38px" name="" id="rateslt" placeholder="完成率" autocomplete="off">
  21. </div>
  22. %
  23. </div>
  24. <div class="layui-inline layui-btn-container">
  25. <button id="selectReload" class="layui-btn layui-btn-sm" lay-event="reload">搜索</button>
  26. </div>
  27. </div>
  28. </script>
  1. <script>
  2. layui.use(['table', 'element'], function () {
  3. var table = layui.table;
  4. var element = layui.element;
  5. $(document).ready(function () {
  6. ProgressFun();
  7. });
  8. function ProgressFun() {
  9. table.render({
  10. elem: '#table_Progress'
  11. , url: '/TestProgress/tableResult'
  12. , page: true //开启分页
  13. , id: 'progressTable'
  14. , autoSort: false
  15. , toolbar: '#toolbarDemo1' //开启头部工具栏,并为其绑定左侧模板
  16. , defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
  17. title: '提示'
  18. , layEvent: 'LAYTABLE_TIPS'
  19. , icon: 'layui-icon-tips'
  20. }]
  21. , cols: [[
  22. { field: 'contractNumber', title: '申请单号', event: 'ProjNumEvent', style: 'color:#359f6a', width: '12%' }
  23. ,{ field: 'projectNum', title: '项目编号', width: '10%' }
  24. , { field: 'projectName', title: '项目名称', width: '30%' }
  25. , { field: 'mathDatas', title: '项目当前进度', width: '48%', sort: true, templet: '#mathDatas' }
  26. ]]
  27. , page: {
  28. theme: '#359f6a',
  29. layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
  30. , first: false
  31. , last: false
  32. }
  33. , limit: 20
  34. , limits: [10, 20, 50, 100]
  35. , done: function () {
  36. element.render()
  37. }
  38. });
  39. }//监听排序事件
  40. table.on('sort(TabevenTest)', function (obj) { //注:sort 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
  41. console.log(obj.field); //当前排序的字段名
  42. console.log(obj.type); //当前排序类型:desc(降序)、asc(升序)、null(空对象,默认排序)
  43. console.log(this);//当前排序的 th 对象
  44. console.log(obj);
  45. //尽管我们的 table 自带排序功能,但并没有请求服务端。
  46. //有些时候,你可能需要根据当前排序的字段,重新向服务端发送请求,从而实现服务端排序,如:
  47. var projectNum = $("#alldes")[0].value;
  48. var rateslt = $("#rateslt")[0].value;
  49. table.reload('progressTable', {
  50. url: '/TestProgress/TableData',
  51. initSort: obj //记录初始排序,如果不设的话,将无法标记表头的排序状态。
  52. , where: { //请求参数(注意:这里面的参数可任意定义,并非下面固定的格式)
  53. field: obj.field //排序字段
  54. , order: obj.type //排序方式
  55. , SearchText: projectNum
  56. , Rateslt: rateslt
  57. }
  58. });
  59. $("#alldes").val(projectNum);
  60. $("#rateslt").val(rateslt);
  61. // layer.msg('服务端排序。order by ' + obj.field + ' ' + obj.type);
  62. });
  63. table.on('toolbar(TabevenTest)', function (obj) { //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
  64. var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
  65. if (layEvent === 'reload') {
  66. var projectNum = $("#alldes")[0].value;
  67. var rateslt = $("#rateslt")[0].value;
  68. var send = {
  69. projectNum: projectNum,
  70. rateslt: rateslt,
  71. }
  72. ProjNumPage(send);
  73. $("#alldes").val(projectNum);
  74. $("#rateslt").val(rateslt);
  75. }
  76. });table.on('tool(TabevenTest)', function (obj) { //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
  77. var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
  78. if (layEvent === 'ProjNumEvent') {
  79. var data = obj.data; //获得当前行数据
  80. var kk = data['contractNumber']; //获取属性uid的值
  81. WindPage(kk);
  82. }
  83. });
  84. function ProjNumPage(send) {
  85. table.reload('progressTable', {
  86. url: '/TestProgress/TableData'
  87. , where: {
  88. SearchText: send.projectNum
  89. , Rateslt: send.rateslt
  90. }
  91. });
  92. }
  93. function WindPage(res) {
  94. layer.open({
  95. type: 2,// 2为iframe
  96. title: 'Edit',// 去掉标题
  97. shade: 0.1,//遮蔽
  98. shadeClose: false, //点击遮罩关闭
  99. maxmin: false, //最大化最小化按钮
  100. closeBtn: true, scrollbar: false,
  101. title: false,//标题栏不可见
  102. area: ['70%', '80%'],//
  103. anim: 5,// 渐变出现
  104. content: '/TestProgress/WindPage?contractNumber=' + res,// iframe链接地址
  105. id: 'name1',
  106. success: function (layero, index) { //成功获得加载changefile.html时,预先加载,将值从父窗口传到 子窗口
  107. // var body = layer.getChildFrame('body', index);//少了这个是不能从父页面向子页面传值的
  108.          获取子页面的元素,进行数据渲染
  109. // body.contents().find("#test").val(res);
  110. },
  111. yes: function (index, layero) {
  112. }
  113. });
  114. }
  115. });
  116. </script>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/158016
推荐阅读
相关标签
  

闽ICP备14008679号