Layui数据表格用法

在这里介绍一下layui数据表格的简单使用,并介绍所踩的坑

首先封装一个类,将数据表格所需要的属性封装在这里

 1  public class MsgJson<T> where T:class,new()
 2     {
 3         //错误提示代号
 4         public int code { get; set; }
 5         //错误提示消息
 6         public string msg { get; set; }
 7         //表格中的记录总数
 8         public int count { get; set; }
 9         //表格中的所有记录
10         public IEnumerable<T> data { get; set; }
11     }

在Controller中创建一个ActionResult类方法

1 public ActionResult Index()
2         {
3             return View();
4         }

然后再创建一个JsonResult类型的方法并填充相应代码

 

 1         public JsonResult GetData()
 2         {
 3             //获取表中所有数据
 4             IEnumerable<Teacher> all = bll.GetAll();
 5             //将该类中的属性进行赋值
 6             MsgJson<Teacher> mo = new MsgJson<Teacher>
 7             {
 8                 code = 0,
 9                 msg="",
10                 data=all,
11                 count=all.Count()
12             };
13             return Json(mo, JsonRequestBehavior.AllowGet);
14         }

 

然后为Index方法添加一个视图,然后添加一个table

 

1 <table id="tea">
2 
3 </table>

 

然后渲染该table

layui.use('table', function () {
        var table = layui.table;
        //此处用于将时间戳转换为时间格式
        var util = layui.util;
        var $ = layui.jquery;
        table.render({
           //指定渲染的表格
            elem: '#tea',
            height: 300,
            //指定数据源,这里是Teacher控制器下的GetData方法
            url: '/Teacher/GetData',
            cols: [[
                { field: 'ID', title: 'ID', width: 80, sort: true },
                { field: 'Name', title: '姓名', width: 100 },
                { field: 'Code', title: '工号', width: 80 },
                {
                    field: 'Sex', title: '性别', width: 80,toolbar:'#sex'
                },
                {
                    field: 'Birthday', title: '出生日期', width: 100, templet: function (d)
                    { return util.toDateString(d.Birthday * 1000); }
                }
            ]],
        })
    })

对于性别的数据使用自定义渲染的方式,改变应显示的数据

 

1 <script type="text/html" id="sex">
2     {{#if(d.sex==1){}}
3     <span>男</span>
4     {{#}else{}}
5     <span>女</span>
6     {{#} }}
7 </script>

 

然后就可以将数据库中的记录显示在网页上了,

 

 

 然后总结一下所踩过的坑,ActionResult类型的方法需要和JsonResult类型的方法中的内容需要分开,也就是说,Index方法只用于创建出一个视图,剩下的从数据库中读取数据的代码就交给JsonResult类型的方法就好了,不然的话,要么有效果没数据,要么只能显示出一堆json格式的数据。

 

posted @ 2020-04-25 14:43  默緣心  阅读(428)  评论(0编辑  收藏  举报