当前位置: 移动技术网 > IT编程>开发语言>.net > 【Bootstrap系列】详解Bootstrap-table

【Bootstrap系列】详解Bootstrap-table

2018年09月11日  | 移动技术网IT编程  | 我要评论

VGA转AV,收获宝官网,石家庄华信学院

本篇文章将与大家分享bootstrap-table插件,借助于它实现基本的增删改查,导入导出,分页,父子表等。

至于其他技术,如冻结表头,列排列,行拖动,列拖动等,会在后续文章中与大家分享。

 一   效果图

(一)页面初始化

下图是页面首次加载结束后的效果,主要完成以下功能:

1.日期部分,开始时间:当前月第一天对应的8位日期,结束时间:当前月最后一天对应的8位日期,时间格式为:yyyy-mm-dd 

2.bootstrap-table加载的数据为日期部分所对应的时间,且按照时间递减展示

(二)查询

1.支持日期查询和订单编号查询

2.当日期和订单编号都存在时,忽略日期条件(因为订单编号是唯一的) 

 

如下为查询结果:

(三)添加

1.利用dialog模态框加载addform页面;

2.实现可拖拽

 

 (四)编辑

1.利用dialog模态框加载editform页面

2.根据订单编号选择编辑

 (五)删除

1.选中删除

(六)导入

1.下载导入模板

2.按照模板格式导入数据

(七)导出

1.选中导出

2.导出支持多种格式

 (八)父子表

1.订单表作为父表,产品表作为子表

2.父表和字表通过产品编号来关联

 

 二   bootstrap-table讲解

关于bootstrap-table参数,需要掌握如下几大类:表格参数,列参数,事件,方法和多语言,

详情可以参考bootstrap-table官网:http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/

三  本demo技术讲解

(一)demo架构图

本demo采用ui+bll+dal+model三层架构。

(二)核心代码

1.bootstrap-table js结构定义

 1 //初始化
 2 var inittable = function (url) {
 3     //先销毁表格
 4     $('#tb_saleorder').bootstraptable("destroy");
 5     //加载表格
 6     $('#tb_saleorder').bootstraptable({
 7         rowstyle: function (row, index) {//row 表示行数据,object,index为行索引,从0开始
 8             var style = "";
 9             if (row.signintime == '' || row.signouttime=='') {
10                 style = { css: { 'color': 'red' } };
11             }
12             return  style;
13         },
14         //searchalign: 'left',
15         //search: true,   //显示隐藏搜索框
16         showheader: true,     //是否显示列头
17         //classes: 'table-no-bordered',
18         showloading: true,
19         undefinedtext: '',
20         showfullscreen: true,
21         toolbaralign: 'left',
22         paginationhalign: 'right',
23         silent: true,
24         url: url,
25         method: 'get',                      //请求方式(*)
26         toolbar: '#toolbar',                //工具按钮用哪个容器
27         striped: true,                      //是否显示行间隔色
28         cache: false,                       //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
29         pagination: true,                   //是否显示分页(*)
30         sortable: false,                     //是否启用排序
31         sortorder: "asc",                   //排序方式
32         //queryparams: inittable.queryparams,  //传递参数(*)
33         sidepagination: "server",           //分页方式:client客户端分页,server服务端分页(*)
34         pagenumber: 1,                       //初始化加载第一页,默认第一页
35         pagesize: 10,                       //每页的记录行数(*)
36         pagelist: [2, 5, 10, 15],        //可供选择的每页的行数(*)
37         search: false,                      //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大
38         strictsearch: true,
39         showcolumns: true,                  //是否显示所有的列
40         showrefresh: true,                  //是否显示刷新按钮
41         minimumcountcolumns: 2,             //最少允许的列数
42         clicktoselect: true,                //是否启用点击选中行
43         //height: 680,                        //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
44         uniqueid: "id",                     //每一行的唯一标识,一般为主键列
45         showtoggle: true,                    //是否显示详细视图和列表视图的切换按钮
46         cardview: false,                    //是否显示详细视图
47         detailview: false,                   //是否显示父子表
48         showexport: true,
49         //exportdatatype: 'all',
50         exportdatatype: "selected",        //导出checkbox选中的行数
51         paginationloop: false,             //是否无限循环
52         columns: [{
53             checkbox: true
54         }, {
55                 field: 'orderno',
56                 title: '订单编号'
57         }, {
58                 field: 'productno',
59                 title: '产品编号'
60         }, {
61                 field: 'custname',
62                 title: '客户姓名'
63         }, {
64                 field: 'custaddress',
65                 title: '客户地址',
66         }, {
67                 field: 'custphone',
68                 title: '客户电话',
69         }, {
70                 field: 'custcompany',
71                 title: '客户公司',
72         }, {
73                 field: 'createdatetime',
74                 title: '订单创建时间',
75         }, {
76                 field: 'updatedatetime',
77                 title: '订单更新时间',
78         }]
79     });
80     return inittable;
81 };
view code

2.订单表增删改查

 1 $(function () {
 2     //初始时间控件
 3     var frstdaydate = getlocalmonfrstdaydate();
 4     var lastdaydate = getlocalmonlastdaydate();
 5     $("#startdate").val(frstdaydate);
 6     $("#enddate").val(lastdaydate);
 7 
 8     //初始化bootstrap-table参数
 9     var filterparam = "";
10     var startdate = $("#startdate").val();
11     var enddate = $("#enddate").val();
12     url = "/salemanage/getorderlist?startdate=" + startdate + "&enddate=" + enddate + "&orderno=" + filterparam + "";
13     inittable(url);
14 
15     //查询数据
16     $("#btn_query").click(function () {
17         var filterparam = $("#querykey").val();
18         var startdate = $("#startdate").val();
19         var enddate = $("#enddate").val();
20         var url = "/salemanage/getorderlist?startdate="+ startdate + "&enddate=" +enddate + "&orderno=" + filterparam + "";
21         inittable(url);
22     })
23 
24     //添加
25     $("#btn_add").click(function () {
26         var url = "/salemanage/addform";
27         opendialog(url, "addform", "添加订单", 645, 470, function (iframe) {
28             top.frames[iframe].acceptclick()
29         });
30     })
31 
32     //编辑
33     $("#btn_edit").click(function () {
34         //获取当前选择行id
35         var selectedrows = $("#tb_saleorder").bootstraptable('getselections');
36         if (selectedrows.length <= 0) {
37             alert('请选择要编辑的数据');
38         } else if (selectedrows.length > 1) {
39             alert('一次只能选择一行数据进行编辑');
40         } else {
41             var keyvalue = selectedrows[0].orderno;
42             var url = "/salemanage/editform?keyvalue=" + keyvalue;
43             opendialog(url, "editform", "编辑邮件", 645, 470, function (iframe) {
44                 top.frames[iframe].acceptclick()
45             });
46         }
47     })
48     //删除数据
49     $("#btn_delete").click(function () {
50         //获取当前选择行id
51         var selectedrows = $("#tb_saleorder").bootstraptable('getselections');
52         if (selectedrows.length <= 0) {
53             alert('请选择要删除的数据');
54             return;
55         }
56         if (selectedrows.length > 1) {
57             alert('一次只能选择一行删除');
58             return;
59         }
60         var orderno = selectedrows[0].orderno;
61         //aja异步请求
62         $.ajax({
63             url: '/salemanage/delorder',
64             type: 'get',
65             contenttype: 'application/json;charset=utf-8',
66             data: { orderno: orderno },
67             success: function (data) {
68                 //刷新bootstrap-table
69                 $("#tb_saleorder").bootstraptable('refresh');
70             },
71             error: function (data) {
72                 alert('数据删除失败' + data);
73             }
74         })
75     })
76 
77     //回车键
78     document.onkeydown = function (e) {
79         if (!e) e = window.event; //火狐中是 window.event
80         if ((e.keycode || e.which) == 13) {
81             var query = document.getelementbyid("btn_query");
82             query.focus();
83             query.click();
84         }
85     }
86 });
view code

3.日期初始化

 1 //当月第一天所对应的日期 yyyy-mm-dd
 2 function getlocalmonfrstdaydate() {
 3     var now = new date();
 4     var year = now.getfullyear();//年
 5     var mon = now.getmonth() + 1;//月
 6     if (mon < 10) {
 7         mon = '-0' + mon;
 8     }
 9     var frstday = "-01"; //日
10     return year + mon + frstday;
11 }
12 //当月最后一天所对应的日期 yyyy-mm-dd
13 function getlocalmonlastdaydate() {
14     var now = new date();
15     var year = now.getfullyear();//年
16     var mon = now.getmonth() + 1;//月
17     if (mon < 10) {
18         mon = '-0' + mon;
19     }
20     var lastday = "-" + getdaycountinmon(year + mon);
21     return year + mon + lastday;
22 }
23 //计算当月对应的最大天数
24 function getdaycountinmon(yearmon) {
25     var arr = yearmon.split("-");
26     var localyear = parseint(arr[0]);
27     var localmon = parseint(arr[1]);
28     var localdate = new date(localyear, localmon, 0);
29     return localdate.getdate();
30 }
view code

4.index.cshtml

 1 @{
 2     layout = "~/views/shared/_layoutbtstable.cshtml";
 3 }
 4 
 5 <!--查询条件-->
 6 <div class="panel-body" style="padding-bottom:0px;width:104%;margin-left:-15px">
 7     <div class="panel panel-default">
 8         <div class="panel-heading">
 9             订单管理
10         </div>
11         <div style="margin-top:-30px;text-align:right">
12             <a href="~/files/importtemple.xlsx" style="margin-right:20px">下载导入模板 </a>
13         </div>
14         <div class="panel-body">
15             <div style="margin-top:10px;">
16                 日期:
17                 <input type="text" id="startdate" style="height:35px;width:100px;margin-left:5px;margin-top:-32px;border-radius: 6px;border: 1px #cccccc solid; outline: none" onfocus="wdatepicker({datefmt:'yyyy-mm-dd'})">
18                 —
19                 <input type="text" id="enddate" style="height:35px;width:100px;margin-left:8px;margin-top:-34px;border-radius: 6px;border: 1px #cccccc solid; outline: none" onfocus="wdatepicker({datefmt:'yyyy-mm-dd'})">
20                 &nbsp; &nbsp;订单编号:<input type="text" id="querykey" placeholder="请输入订单编号进行查询" style="height:35px;width:170px;margin-left:10px;margin-top:-34px;border-radius: 6px;border: 1px #cccccc solid; outline: none">
21                 <button type="button" style="width:70px;height:35px;margin-left:20px;margin-top:-3px" id="btn_query" class="btn btn-success">查询</button>
22                 <button type="button" style="width:70px;height:35px;margin-left:20px;margin-top:-3px" id="btn_add" class="btn btn-info">添加</button>
23                 <button type="button" style="width:70px;height:35px;margin-left:20px;margin-top:-3px" id="btn_edit" class="btn btn-warning">编辑</button>
24                 <button type="button" style="width:70px;height:35px;margin-left:20px;margin-top:-3px" id="btn_delete" class="btn btn-danger">删除</button>
25             </div>
26         </div>
27     </div>
28 </div>
29 <!--初始化bootstrap-table-->
30 <div style="margin-bottom:-40px;color:red">注释:订单数据</div>
31 <table id="tb_saleorder" class="table"></table>
32 
33 <style>
34     #tb_saleorder tbody > tr:hover {
35         background-color: #449d44;
36     }
37 
38     #tb_saleorder > thead th {
39         padding: 0;
40         margin: 0;
41         background-color: #d9edf7;
42     }
43 </style>
44 <script>
45     //刷新bootstrap-table
46     function refleshbootstraptable() {
47         $("#tb_saleorder").bootstraptable('refresh');
48     }
49 </script>
50 
51 <script src="~/customui/tablejs/saleorder.js"></script>
view code

5.addform.cshtml

 1 @{
 2     viewbag.title = "addform";
 3     layout = "~/views/shared/_layoutbtstable.cshtml";
 4 }
 5 
 6 <script>
 7     //添加数据
 8     function acceptclick() {
 9         var orderno = $("#orderno").val();
10         var productno = $("#productno").val();
11         var custname = $("#custname").val();
12         var custaddress = $("#custaddress").val();
13         var custphone = $("#custphone").val();
14         var custcompany = $("#custcompany").val();
15         var createdatetime = $("#createdatetime").val();
16         var updatedatetime = $("#updatedatetime").val();
17         $.ajax({
18             url: '/salemanage/adddatatodb',
19             type: 'get',
20             contenttype: 'application/json;charset=utf-8',
21             data: {
22                 'orderno': orderno, 'productno': productno, 'custname': custname,
23                 'custaddress': custaddress, 'custphone': custphone, 'custcompany': custcompany,
24                 'createdatetime': createdatetime, 'updatedatetime': updatedatetime
25             },
26             success: function (data) {
27                 reflesh();
28                 //关闭对话框
29                 closedialog();
30             },
31             error: function (data) {
32                 alert('添加数据失败' + data);
33             }
34         })
35     }
36     //刷新
37     function reflesh() {
38         window.parent.refleshbootstraptable();
39     }
40 </script>
41 
42 
43 <div class="table" style="width:100%;margin-top:10px">
44     <table id="tb_saleorder_add" class="table text-nowrap" style="text-align:right;">
45         <tr>
46             <td style="height:35px;line-height:35px">订单编号&nbsp;&nbsp;&nbsp;:</td>
47             <td><input type="text" id="orderno" style="width:500px;" /></td>
48         </tr>
49         <tr>
50             <td style="height:35px;line-height:35px">产品名称&nbsp;&nbsp;&nbsp;:</td>
51             <td><input type="text" id="productno" style="width:500px;" /></td>
52         </tr>
53         <tr>
54             <td style="height:35px;line-height:35px">客户姓名&nbsp;&nbsp;&nbsp;:</td>
55             <td><input type="text" id="custname" style="width:500px;" /></td>
56         </tr>
57         <tr>
58             <td style="height:35px;line-height:35px">客户地址&nbsp;&nbsp;&nbsp;:</td>
59             <td><input type="text" id="custaddress" style="width:500px;" /></td>
60         </tr>
61         <tr>
62             <td style="height:35px;line-height:35px">客户电话&nbsp;&nbsp;&nbsp;:</td>
63             <td><input type="text" id="custphone" style="width:500px;" /></td>
64         </tr>
65         <tr>
66             <td style="height:35px;line-height:35px">客户公司&nbsp;&nbsp;&nbsp;:</td>
67             <td><input type="text" id="custcompany" style="width:500px;" /></td>
68         </tr>
69         <tr>
70             <td style="height:35px;line-height:35px">订单创建时间&nbsp;&nbsp;&nbsp;:</td>
71             <td><input type="text" id="createdatetime" style="width:500px;" onfocus="wdatepicker({datefmt:'yyyy-mm-dd hh:mm:ss'})" class="wdate"/></td>
72         </tr>
73         <tr>
74             <td style="height:35px;line-height:35px">订单更新时间&nbsp;&nbsp;&nbsp;:</td>
75             <td><input type="text" id="updatedatetime" style="width:500px;" onfocus="wdatepicker({datefmt:'yyyy-mm-dd hh:mm:ss'})" class="wdate"/></td>
76         </tr>
77     </table>
78 </div>
79 
80 <style>
81     #tb_saleorder_add td input[type=text] {
82         height: 35px;
83         border-radius: 6px;
84         border: 1px #cccccc solid;
85         outline: none
86     }
87 </style>
view code

6.editform.cshtml

@{
    viewbag.title = "editform";
    layout = "~/views/shared/_layoutbtstable.cshtml";
}

<script>
    $(function () {
        //初始化页面控件
        $.ajax({
            url: "/salemanage/initmodifysheet",
            type: 'get',
            contenttype: 'application/json;charset=utf-8',
            data: {
                orderno: getquery('keyvalue')
            },
            success: function (data) {
                //将回调数据转化为json对象
                var jsondata = eval(data);
                //遍历,为表单赋值
                $("#orderno").val(jsondata[0].orderno);
                $("#productno").val(jsondata[0].productno);  
                $("#custname").val(jsondata[0].custname);
                $("#custaddress").val(jsondata[0].custaddress);
                $("#custphone").val(jsondata[0].custphone);
                $("#custcompany").val(jsondata[0].custcompany);
                $("#createdatetime").val(jsondata[0].createdatetime);
                $("#updatedatetime").val(jsondata[0].updatedatetime); 
            },
            error: function (data) {
                alert('编辑数据失败' + data);
            }
        })
    })

    //添加数据
    function acceptclick() {
        var orderno = $("#orderno").val();
        var productno = $("#productno").val();
        var custname = $("#custname").val();
        var custaddress = $("#custaddress").val();
        var custphone = $("#custphone").val();
        var custcompany = $("#custcompany").val();
        var createdatetime = $("#createdatetime").val();
        var updatedatetime = $("#updatedatetime").val();
        $.ajax({
            url: '/salemanage/modifydatatodb',
            type: 'get',
            contenttype: 'application/json;charset=utf-8',
            data: {
                'orderno': orderno, 'productno': productno, 'custname': custname,
                'custaddress': custaddress, 'custphone': custphone, 'custcompany': custcompany,
                'createdatetime': createdatetime, 'updatedatetime': updatedatetime
            },
            success: function (data) {
                reflesh();
                //关闭对话框
                closedialog();
            },
            error: function (data) {
                alert('添加数据失败' + data);
            }
        })
    }
    //刷新
    function reflesh() {
        window.parent.refleshbootstraptable();
    }
</script>



<div class="table" style="width:100%;margin-top:10px">
    <table id="tb_saleorder_add" class="table text-nowrap" style="text-align:right;">
        <tr>
            <td style="height:35px;line-height:35px">订单编号&nbsp;&nbsp;&nbsp;:</td>
            <td><input type="text" id="orderno" style="width:500px;" disabled/></td>
        </tr>
        <tr>
            <td style="height:35px;line-height:35px">产品名称&nbsp;&nbsp;&nbsp;:</td>
            <td><input type="text" id="productno" style="width:500px;" /></td>
        </tr>
        <tr>
            <td style="height:35px;line-height:35px">客户姓名&nbsp;&nbsp;&nbsp;:</td>
            <td><input type="text" id="custname" style="width:500px;" /></td>
        </tr>
        <tr>
            <td style="height:35px;line-height:35px">客户地址&nbsp;&nbsp;&nbsp;:</td>
            <td><input type="text" id="custaddress" style="width:500px;" /></td>
        </tr>
        <tr>
            <td style="height:35px;line-height:35px">客户电话&nbsp;&nbsp;&nbsp;:</td>
            <td><input type="text" id="custphone" style="width:500px;" /></td>
        </tr>
        <tr>
            <td style="height:35px;line-height:35px">客户公司&nbsp;&nbsp;&nbsp;:</td>
            <td><input type="text" id="custcompany" style="width:500px;" /></td>
        </tr>
        <tr>
            <td style="height:35px;line-height:35px">订单创建时间&nbsp;&nbsp;&nbsp;:</td>
            <td><input type="text" id="createdatetime" style="width:500px;" onfocus="wdatepicker({datefmt:'yyyy-mm-dd hh:mm:ss'})" class="wdate" /></td>
        </tr>
        <tr>
            <td style="height:35px;line-height:35px">订单更新时间&nbsp;&nbsp;&nbsp;:</td>
            <td><input type="text" id="updatedatetime" style="width:500px;" onfocus="wdatepicker({datefmt:'yyyy-mm-dd hh:mm:ss'})" class="wdate" /></td>
        </tr>
    </table>
</div>

<style>
    #tb_saleorder_add td input[type=text] {
        height: 35px;
        border-radius: 6px;
        border: 1px #cccccc solid;
        outline: none
    }
</style>
view code

7.import.cshtml

  1 @{
  2     viewbag.title = "editform";
  3     layout = "~/views/shared/_layoutbtstable.cshtml";
  4 }
  5 
  6 <script>
  7     $(function () {
  8         //初始化页面控件
  9         $.ajax({
 10             url: "/salemanage/initmodifysheet",
 11             type: 'get',
 12             contenttype: 'application/json;charset=utf-8',
 13             data: {
 14                 orderno: getquery('keyvalue')
 15             },
 16             success: function (data) {
 17                 //将回调数据转化为json对象
 18                 var jsondata = eval(data);
 19                 //遍历,为表单赋值
 20                 $("#orderno").val(jsondata[0].orderno);
 21                 $("#productno").val(jsondata[0].productno);  
 22                 $("#custname").val(jsondata[0].custname);
 23                 $("#custaddress").val(jsondata[0].custaddress);
 24                 $("#custphone").val(jsondata[0].custphone);
 25                 $("#custcompany").val(jsondata[0].custcompany);
 26                 $("#createdatetime").val(jsondata[0].createdatetime);
 27                 $("#updatedatetime").val(jsondata[0].updatedatetime); 
 28             },
 29             error: function (data) {
 30                 alert('编辑数据失败' + data);
 31             }
 32         })
 33     })
 34 
 35     //添加数据
 36     function acceptclick() {
 37         var orderno = $("#orderno").val();
 38         var productno = $("#productno").val();
 39         var custname = $("#custname").val();
 40         var custaddress = $("#custaddress").val();
 41         var custphone = $("#custphone").val();
 42         var custcompany = $("#custcompany").val();
 43         var createdatetime = $("#createdatetime").val();
 44         var updatedatetime = $("#updatedatetime").val();
 45         $.ajax({
 46             url: '/salemanage/modifydatatodb',
 47             type: 'get',
 48             contenttype: 'application/json;charset=utf-8',
 49             data: {
 50                 'orderno': orderno, 'productno': productno, 'custname': custname,
 51                 'custaddress': custaddress, 'custphone': custphone, 'custcompany': custcompany,
 52                 'createdatetime': createdatetime, 'updatedatetime': updatedatetime
 53             },
 54             success: function (data) {
 55                 reflesh();
 56                 //关闭对话框
 57                 closedialog();
 58             },
 59             error: function (data) {
 60                 alert('添加数据失败' + data);
 61             }
 62         })
 63     }
 64     //刷新
 65     function reflesh() {
 66         window.parent.refleshbootstraptable();
 67     }
 68 </script>
 69 
 70 
 71 
 72 <div class="table" style="width:100%;margin-top:10px">
 73     <table id="tb_saleorder_add" class="table text-nowrap" style="text-align:right;">
 74         <tr>
 75             <td style="height:35px;line-height:35px">订单编号&nbsp;&nbsp;&nbsp;:</td>
 76             <td><input type="text" id="orderno" style="width:500px;" disabled/></td>
 77         </tr>
 78         <tr>
 79             <td style="height:35px;line-height:35px">产品名称&nbsp;&nbsp;&nbsp;:</td>
 80             <td><input type="text" id="productno" style="width:500px;" /></td>
 81         </tr>
 82         <tr>
 83             <td style="height:35px;line-height:35px">客户姓名&nbsp;&nbsp;&nbsp;:</td>
 84             <td><input type="text" id="custname" style="width:500px;" /></td>
 85         </tr>
 86         <tr>
 87             <td style="height:35px;line-height:35px">客户地址&nbsp;&nbsp;&nbsp;:</td>
 88             <td><input type="text" id="custaddress" style="width:500px;" /></td>
 89         </tr>
 90         <tr>
 91             <td style="height:35px;line-height:35px">客户电话&nbsp;&nbsp;&nbsp;:</td>
 92             <td><input type="text" id="custphone" style="width:500px;" /></td>
 93         </tr>
 94         <tr>
 95             <td style="height:35px;line-height:35px">客户公司&nbsp;&nbsp;&nbsp;:</td>
 96             <td><input type="text" id="custcompany" style="width:500px;" /></td>
 97         </tr>
 98         <tr>
 99             <td style="height:35px;line-height:35px">订单创建时间&nbsp;&nbsp;&nbsp;:</td>
100             <td><input type="text" id="createdatetime" style="width:500px;" onfocus="wdatepicker({datefmt:'yyyy-mm-dd hh:mm:ss'})" class="wdate" /></td>
101         </tr>
102         <tr>
103             <td style="height:35px;line-height:35px">订单更新时间&nbsp;&nbsp;&nbsp;:</td>
104             <td><input type="text" id="updatedatetime" style="width:500px;" onfocus="wdatepicker({datefmt:'yyyy-mm-dd hh:mm:ss'})" class="wdate" /></td>
105         </tr>
106     </table>
107 </div>
108 
109 <style>
110     #tb_saleorder_add td input[type=text] {
111         height: 35px;
112         border-radius: 6px;
113         border: 1px #cccccc solid;
114         outline: none
115     }
116 </style>
view code

8.parentandchild.cshtml

 1 @{
 2     layout = "~/views/shared/_layoutbtstable.cshtml";
 3 }
 4 
 5 <!--查询条件-->
 6 <div class="panel-body" style="padding-bottom:0px;width:104%;margin-left:-15px">
 7     <div class="panel panel-default">
 8         <div class="panel-heading">
 9             订单管理
10         </div>
11         <div style="margin-top:-30px;text-align:right">
12             <a href="~/files/importtemple.xlsx" style="margin-right:20px">下载导入模板 </a>
13         </div>
14         <div class="panel-body">
15             <div style="margin-top:10px;">
16                 日期:
17                 <input type="text" id="startdate" style="height:35px;width:100px;margin-left:5px;margin-top:-32px;border-radius: 6px;border: 1px #cccccc solid; outline: none" onfocus="wdatepicker({datefmt:'yyyy-mm-dd'})">
18                 —
19                 <input type="text" id="enddate" style="height:35px;width:100px;margin-left:8px;margin-top:-34px;border-radius: 6px;border: 1px #cccccc solid; outline: none" onfocus="wdatepicker({datefmt:'yyyy-mm-dd'})">
20                 &nbsp; &nbsp;订单编号:<input type="text" id="querykey" placeholder="请输入订单编号进行查询" style="height:35px;width:170px;margin-left:10px;margin-top:-34px;border-radius: 6px;border: 1px #cccccc solid; outline: none">
21                 <button type="button" style="width:70px;height:35px;margin-left:20px;margin-top:-3px" id="btn_query" class="btn btn-success">查询</button>
22                 <button type="button" style="width:70px;height:35px;margin-left:20px;margin-top:-3px" id="btn_add" class="btn btn-info">添加</button>
23                 <button type="button" style="width:70px;height:35px;margin-left:20px;margin-top:-3px" id="btn_edit" class="btn btn-warning">编辑</button>
24                 <button type="button" style="width:70px;height:35px;margin-left:20px;margin-top:-3px" id="btn_delete" class="btn btn-danger">删除</button>
25             </div>
26         </div>
27     </div>
28 </div>
29 <!--初始化bootstrap-table-->
30 <div style="margin-bottom:-40px;color:red">注释:父子表</div>
31 <table id="tb_saleorder" class="table"></table>
32 
33 <style>
34     #tb_saleorder > thead th {
35         padding: 0;
36         margin: 0;
37         background-color: #d9edf7;
38     }
39 </style>
40 <script>
41     //刷新bootstrap-table
42     function refleshbootstraptable() {
43         $("#tb_saleorder").bootstraptable('refresh');
44     }
45 </script>
46 
47 <script src="~/customui/tablejs/parentchild.js"></script>
view code

9.布局页 _layoutbtstable.cshtml

 1 <!doctype html>
 2 
 3 <html>
 4 <head>
 5     <meta name="viewport" content="width=device-width" />
 6     <link href="~/customui/bootstrap/css/bootstrap.css" rel="stylesheet" />
 7     <link href="~/customui/bootstraptable/bootstrap-table.css" rel="stylesheet" />
 8     <link href="~/customui/skin/wdatepicker.css" rel="stylesheet" />
 9     <script src="~/customui/jquery/jquery-3.3.1.js"></script>
10     <script src="~/customui/lhgdialog/lhgdialog.min.js"></script>
11     <script src="~/customui/bootstrap/js/bootstrap.js"></script>
12     <script src="~/customui/bootstraptable/bootstrap-table.js"></script>
13     <script src="~/customui/bootstraptable/tableexport.js"></script>
14     <script src="~/customui/bootstraptable/bootstrap-table-export.js"></script>
15     <script src="~/customui/bootstraptable/bootstrap-table-zh-cn.js"></script>
16     <script src="~/customui/datepicker/wdatepicker.js"></script>
17 </head>
18 <body>
19     <div>
20         @renderbody()
21     </div>
22 </body>
23 </html>
24 
25 <script src="~/customui/tablejs/dialogtemple.js"></script>
view code

10.importexceltodb.cs

  1 using system;
  2 using system.collections.generic;
  3 using system.configuration;
  4 using system.data;
  5 using system.data.oledb;
  6 using system.data.sqlclient;
  7 using system.linq;
  8 using system.text;
  9 using system.web;
 10 
 11 namespace btstraptb.common
 12 {
 13     public class importexceltodb
 14     {
 15         //全局数据库连接字符串
 16         private readonly string strconnection = configurationmanager.connectionstrings["constr"].connectionstring;
 17 
 18         //从excel读取数据
 19         public static dataset readexceldatatotable(string filepath)
 20         {
 21             try
 22             {
 23                 int index1 = filepath.lastindexof("\\");
 24                 int index2 = filepath.lastindexof(".");
 25                 string filename ="["+filepath.substring(index1+1,index2-index1-1)+"$]";
 26                 string strconn = string.format("provider=microsoft.ace.oledb.12.0;data source={0};extended properties='excel 8.0;hdr=yes;imex=1;'", filepath);
 27                 using (oledbconnection oleconn = new oledbconnection(strconn))
 28                 {
 29                     oleconn.open();
 30                     string sql = "select * from "+filename+ "";
 31                     oledbdataadapter oledaexcel = new oledbdataadapter(sql, oleconn);
 32                     dataset oledsexcel = new dataset();
 33                     oledaexcel.fill(oledsexcel, "table1");
 34                     return oledsexcel;
 35                 }
 36             }
 37             catch (exception ex)
 38             {
 39                 throw ex;
 40             }
 41         }
 42         public void insertexceldatatodb(string filename)
 43         {
 44             //导入表格格式化sql
 45             string sqltext = @"insert into [dbo].[saleorder]
 46                                ([orderno]
 47                                ,[productno]
 48                                ,[custname]
 49                                ,[custaddress]
 50                                ,[custphone]
 51                                ,[custcompany]
 52                                ,[createdatetime]
 53                                ,[updatedatetime])
 54                                values
 55                                 ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')";
 56 
 57             if (!system.io.file.exists(filename))
 58             {
 59                 throw new exception("指定路径的excel文件不存在!");
 60             }
 61             dataset ds = readexceldatatotable(filename);
 62             datatable dt = ds.tables[0];
 63             //将excel数据插入到db之前,先判断db中是否存在数据
 64             deldbrepeatdata(dt);
 65             list<string> list = (from datarow row in dt.rows
 66                                  select string.format(sqltext, row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7])).tolist();
 67             operatedb(list);
 68         }
 69 
 70         /*
 71          将excel数据插入到db之前,
 72          先判断db中是否存在同一天同一员工记录
 73        */
 74         public int deldbrepeatdata(datatable dt)
 75         {
 76             //sql脚本
 77             string delsqltext = @"delete from [dbo].[saleorder]
 78                                   where orderno in ('{0}')
 79                                   ";
 80 
 81             //取excel中的员工号和打卡日期
 82             stringbuilder strbld = new stringbuilder();
 83 
 84             for (int i = 0; i < dt.rows.count; i++)
 85             {
 86                 strbld.append(dt.rows[i][0]);
 87                 
 88             }
 89 
 90             list<string> list = (from datarow row in dt.rows
 91                                  select string.format(delsqltext, row[0])).tolist();
 92 
 93             operatedb(list);
 94             return 0;
 95         }
 96 
 97         //db操作
 98         public int operatedb(list<string> list)
 99         {
100             int result = 0;
101             using (sqlconnection conn = new sqlconnection(strconnection))
102             {
103                 if (conn.state==connectionstate.closed)
104                 {
105                     conn.open();
106                 }
107                 foreach (string item in list)
108                 {
109                     sqlcommand cmd = new sqlcommand(item, conn);
110                     result=cmd.executenonquery();
111                 }
112             }
113             return result;
114         }
115     }
116 }
view code

12.converthelpers.cs

 1 using newtonsoft.json;
 2 using system;
 3 using system.collections.generic;
 4 using system.data;
 5 using system.linq;
 6 using system.reflection;
 7 using system.web;
 8 
 9 namespace btstraptb.common
10 {
11     /// <summary>
12     /// 转换json格式帮助类
13     /// </summary>
14     public static class jsonhelper
15     {
16         public static object tojson(this string json)
17         {
18             return jsonconvert.deserializeobject(json);
19         }
20         public static string tojson(this object obj)
21         {
22             return jsonconvert.serializeobject(obj);
23         }
24         public static list<t> jonstolist<t>(this string json)
25         {
26             return jsonconvert.deserializeobject<list<t>>(json);
27         }
28         public static t jsontoentity<t>(this string json)
29         {
30             return jsonconvert.deserializeobject<t>(json);
31         }
32     }
33 }
view code

13.salemanagecontroller

 1 using btstraptb.bll;
 2 using btstraptb.common;
 3 using btstraptb.models;
 4 using system;
 5 using system.collections.generic;
 6 using system.io;
 7 using system.linq;
 8 using system.web;
 9 using system.web.mvc;
10 
11 namespace btstraptb.controllers
12 {
13     //销售管理
14     public class salemanagecontroller : basemanagecontroller
15     {
16         importexceltodb importtoexcl = new importexceltodb();
17         saleorderbll sobll = new saleorderbll();
18         saleproductbll spbll = new saleproductbll();
19         public override actionresult index()
20         {
21             return view();
22         }
23         //导入页面
24         public actionresult import()
25         {
26             return view();
27         }
28 
29         //将excel订单数据导入
30         [httppost]
31         public actionresult importexcltodb(httppostedfilebase file)
32         {
33             var severpath = this.server.mappath("/files"); //获取当前虚拟文件路径
34             var savepath = path.combine(severpath, file.filename); //拼接保存文件路径
35             file.saveas(savepath);
36             try
37             {
38                 importtoexcl.insertexceldatatodb(savepath);
39                 return content("<script>alert('上传成功!!')</script>");
40             }
41             catch (exception ex)
42             {
43                 throw new exception(ex.message);
44             }
45 
46             //response.redirect("/punchcardrecord/index");
47         }
48 
49         //父子页面
50         public actionresult parentandchild()
51         {
52             return view();
53         }
54         
55         //获取子表数据
56         public actionresult getchilddatalist(int limit, int offset,string productno)
57         {
58             list<saleproduct> list = spbll.getproductorderlist(productno);
59             int total = list.count;
60             var rows = list.skip(offset).take(limit).tolist();
61             return json(new { total, rows }, jsonrequestbehavior.allowget);
62         }
63 
64         //获取订单列表
65         public actionresult getorderlist(int limit, int offset,string startdate,string enddate,string orderno)
66         {
67             list<saleorder> list = sobll.getsaleorderlist(startdate,enddate, orderno);
68             int total = list.count;
69             var rows = list.skip(offset).take(limit).tolist();
70             return json(new { total, rows }, jsonrequestbehavior.allowget);
71         }
72         //删除数据
73         public void delorder(string orderno)
74         {
75             sobll.deldatatodb(orderno);
76         }
77         //添加数据
78         public void adddatatodb(saleorder saleorder)
79         {
80             sobll.adddatatodb(saleorder);
81         }
82         //初始化修改表单
83         public actionresult initmodifysheet(string orderno)
84         {
85             list<saleorder> list = sobll.getsaleorderlist("", "", orderno);
86             return content(list.tojson());
87         }
88         //修改数据
89         public void modifydatatodb(saleorder saleorder)
90         {
91             sobll.modifydatatodb(saleorder);
92         }
93     }
94 }
view code

14.父子表js

  1 //初始化
  2 var inittable = function (url) {
  3     //先销毁表格
  4     $('#tb_saleorder').bootstraptable("destroy");
  5     //加载表格
  6     $('#tb_saleorder').bootstraptable({
  7         rowstyle: function (row, index) {//row 表示行数据,object,index为行索引,从0开始
  8             var style = "";
  9             if (row.signintime == '' || row.signouttime == '') {
 10                 style = { css: { 'color': 'red' } };
 11             }
 12             return style;
 13         },
 14         //searchalign: 'left',
 15         //search: true,   //显示隐藏搜索框
 16         showheader: true,     //是否显示列头
 17         //classes: 'table-no-bordered',
 18         showloading: true,
 19         undefinedtext: '',
 20         showfullscreen: true,
 21         toolbaralign: 'left',
 22         paginationhalign: 'right',
 23         silent: true,
 24         url: url,
 25         method: 'get',                      //请求方式(*)
 26         toolbar: '#toolbar',                //工具按钮用哪个容器
 27         striped: true,                      //是否显示行间隔色
 28         cache: false,                       //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
 29         pagination: true,                   //是否显示分页(*)
 30         sortable: false,                     //是否启用排序
 31         sortorder: "asc",                   //排序方式
 32         //queryparams: inittable.queryparams,  //传递参数(*)
 33         sidepagination: "server",           //分页方式:client客户端分页,server服务端分页(*)
 34         pagenumber: 1,                       //初始化加载第一页,默认第一页
 35         pagesize: 10,                       //每页的记录行数(*)
 36         pagelist: [2, 5, 10, 15],        //可供选择的每页的行数(*)
 37         search: false,                      //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大
 38         strictsearch: true,
 39         showcolumns: true,                  //是否显示所有的列
 40         showrefresh: true,                  //是否显示刷新按钮
 41         minimumcountcolumns: 2,             //最少允许的列数
 42         clicktoselect: true,                //是否启用点击选中行
 43         //height: 680,                        //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
 44         uniqueid: "id",                     //每一行的唯一标识,一般为主键列
 45         showtoggle: true,                    //是否显示详细视图和列表视图的切换按钮
 46         cardview: false,                    //是否显示详细视图
 47         detailview: true,                   //是否显示父子表
 48         showexport: true,
 49         //exportdatatype: 'all',
 50         exportdatatype: "selected",        //导出checkbox选中的行数
 51         paginationloop: false,             //是否无限循环
 52         columns: [{
 53             checkbox: true
 54         }, {
 55             field: 'orderno',
 56             title: '订单编号'
 57         }, {
 58             field: 'productno',
 59             title: '产品编号'
 60         }, {
 61             field: 'custname',
 62             title: '客户姓名'
 63         }, {
 64             field: 'custaddress',
 65             title: '客户地址',
 66         }, {
 67             field: 'custphone',
 68             title: '客户电话',
 69         }, {
 70             field: 'custcompany',
 71             title: '客户公司',
 72         }, {
 73             field: 'createdatetime',
 74             title: '订单创建时间',
 75         }, {
 76             field: 'updatedatetime',
 77             title: '订单更新时间',
 78         }],
 79 
 80         //无限循环取子表,直到子表里面没有记录
 81           onexpandrow: function (index, row, $subdetail) {
 82             initsubtable(index, row, $subdetail);
 83         }
 84     });
 85     return inittable;
 86 
 87     
 88 };
 89 
 90 //初始化子表格(无线循环)
 91 initsubtable = function (index, row, $detail) {
 92     var parentid = row.productno;
 93     var cur_table = $detail.html('<table></table>').find('table');
 94     $(cur_table).bootstraptable({
 95         url: "/salemanage/getchilddatalist",
 96         method: 'get',
 97         queryparams: { 'limit':10000,'offset':0,'productno':parentid},
 98         clicktoselect: true,
 99         detailview: false,//父子表
100         sidepagination: "server",
101         uniqueid: "productno",
102         pagesize: 10,
103         pagelist: [10, 25],
104         columns: [{
105             field: 'productno',
106             title: '产品编号'
107         },
108         {
109             field: 'productname',
110             title: '产品名称'
111         }, {
112             field: 'producttype',
113             title: '产品类型'
114         }, {
115             field: 'productcount',
116             title: '产品数量'
117         },
118         {
119             field: 'productprice',
120             title: '产品单价'
121         }],
122         //无限循环取子表,直到子表里面没有记录
123         onexpandrow: function (index, row, $subdetail) {
124             initsubtable(index, row, $subdetail);
125         }
126     });
127 };
view code

(三)其他技术点

1.改变bootstrap-table表头颜色

1 #tb_saleorder > thead th {
2         padding: 0;
3         margin: 0;
4         background-color: #d9edf7;
5     }

2.改变bootstrap-table 光标悬停颜色

1 #tb_saleorder tbody > tr:hover {
2         background-color: #449d44;
3     }

3.刷新bootstrap-table

1 //刷新bootstrap-table
2     function refleshbootstraptable() {
3         $("#tb_saleorder").bootstraptable('refresh');
4     }

 4.弹窗

 1 /*
 2 弹出对话框(带:确认按钮、取消按钮)
 3 */
 4 function opendialog(url, _id, _title, _width, _height, callback) {
 5     loading(true);
 6     top.$.dialog({
 7         id: _id,
 8         width: _width,
 9         height: _height,
10         max: false,
11         lock: true,
12         title: _title,
13         resize: false,
14         extenddrag: true,
15         content: 'url:' + rootpath() + url,
16         ok: function () {
17             callback(_id);
18             return false;
19         },
20         cancel: true
21     });
22 }

5.bootstrap-table核心技术点,再次强调

 1 var inittable = function (url) {
 2     //先销毁表格
 3     $('#tb_saleorder').bootstraptable("destroy");
 4     //加载表格
 5     $('#tb_saleorder').bootstraptable({
 6         rowstyle: function (row, index) {//row 表示行数据,object,index为行索引,从0开始
 7             var style = "";
 8             if (row.signintime == '' || row.signouttime=='') {
 9                 style = { css: { 'color': 'red' } };
10             }
11             return  style;
12         },
13         //searchalign: 'left',
14         //search: true,   //显示隐藏搜索框
15         showheader: true,     //是否显示列头
16         //classes: 'table-no-bordered',
17         showloading: true,
18         undefinedtext: '',
19         showfullscreen: true,
20         toolbaralign: 'left',
21         paginationhalign: 'right',
22         silent: true,
23         url: url,
24         method: 'get',                      //请求方式(*)
25         toolbar: '#toolbar',                //工具按钮用哪个容器
26         striped: true,                      //是否显示行间隔色
27         cache: false,                       //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
28         pagination: true,                   //是否显示分页(*)
29         sortable: false,                     //是否启用排序
30         sortorder: "asc",                   //排序方式
31         //queryparams: inittable.queryparams,  //传递参数(*)
32         sidepagination: "server",           //分页方式:client客户端分页,server服务端分页(*)
33         pagenumber: 1,                       //初始化加载第一页,默认第一页
34         pagesize: 10,                       //每页的记录行数(*)
35         pagelist: [2, 5, 10, 15],        //可供选择的每页的行数(*)
36         search: false,                      //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大
37         strictsearch: true,
38         showcolumns: true,                  //是否显示所有的列
39         showrefresh: true,                  //是否显示刷新按钮
40         minimumcountcolumns: 2,             //最少允许的列数
41         clicktoselect: true,                //是否启用点击选中行
42         //height: 680,                        //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
43         uniqueid: "id",                     //每一行的唯一标识,一般为主键列
44         showtoggle: true,                    //是否显示详细视图和列表视图的切换按钮
45         cardview: false,                    //是否显示详细视图
46         detailview: false,                   //是否显示父子表
47         showexport: true,
48         //exportdatatype: 'all',
49         exportdatatype: "selected",        //导出checkbox选中的行数
50         paginationloop: false,             //是否无限循环
51         columns: [{
52             checkbox: true
53         }, {
54                 field: 'orderno',
55                 title: '订单编号'
56         }, {
57                 field: 'productno',
58                 title: '产品编号'
59         }, {
60                 field: 'custname',
61                 title: '客户姓名'
62         }, {
63                 field: 'custaddress',
64                 title: '客户地址',
65         }, {
66                 field: 'custphone',
67                 title: '客户电话',
68         }, {
69                 field: 'custcompany',
70                 title: '客户公司',
71         }, {
72                 field: 'createdatetime',
73                 title: '订单创建时间',
74         }, {
75                 field: 'updatedatetime',
76                 title: '订单更新时间',
77         }]
78     });
79     return inittable;
80 };

四  写在最后

  本片文章借助于bootstrap-table插件,实现了基本的增删改查,导入导出,分页,父子表等。至于其他技术,如冻结表头,列排列,行拖动,列拖动等,会在后续文章中与大家分享。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网