【Bootstrap系列】詳解Bootstrap-table
本篇文章將與大家分享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({ 7rowStyle: function (row, index) {//row 表示行資料,object,index為行索引,從0開始 8var style = ""; 9if (row.SignInTime == '' || row.SignOutTime=='') { 10style = { css: { 'color': 'red' } }; 11} 12returnstyle; 13}, 14//searchAlign: 'left', 15//search: true,//顯示隱藏搜尋框 16showHeader: true,//是否顯示列頭 17//classes: 'table-no-bordered', 18showLoading: true, 19undefinedText: '', 20showFullscreen: true, 21toolbarAlign: 'left', 22paginationHAlign: 'right', 23silent: true, 24url: url, 25method: 'get',//請求方式(*) 26toolbar: '#toolbar',//工具按鈕用哪個容器 27striped: true,//是否顯示行間隔色 28cache: false,//是否使用快取,預設為true,所以一般情況下需要設定一下這個屬性(*) 29pagination: true,//是否顯示分頁(*) 30sortable: false,//是否啟用排序 31sortOrder: "asc",//排序方式 32//queryParams: InitTable.queryParams,//傳遞引數(*) 33sidePagination: "server",//分頁方式:client客戶端分頁,server服務端分頁(*) 34pageNumber: 1,//初始化載入第一頁,預設第一頁 35pageSize: 10,//每頁的記錄行數(*) 36pageList: [2, 5, 10, 15],//可供選擇的每頁的行數(*) 37search: false,//是否顯示錶格搜尋,此搜尋是客戶端搜尋,不會進服務端,所以,個人感覺意義不大 38strictSearch: true, 39showColumns: true,//是否顯示所有的列 40showRefresh: true,//是否顯示重新整理按鈕 41minimumCountColumns: 2,//最少允許的列數 42clickToSelect: true,//是否啟用點選選中行 43//height: 680,//行高,如果沒有設定height屬性,表格自動根據記錄條數覺得表格高度 44uniqueId: "ID",//每一行的唯一標識,一般為主鍵列 45showToggle: true,//是否顯示詳細檢視和列表檢視的切換按鈕 46cardView: false,//是否顯示詳細檢視 47detailView: false,//是否顯示父子表 48showExport: true, 49//exportDataType: 'all', 50exportDataType: "selected",//匯出checkbox選中的行數 51paginationLoop: false,//是否無限迴圈 52columns: [{ 53checkbox: true 54}, { 55field: 'OrderNO', 56title: '訂單編號' 57}, { 58field: 'ProductNo', 59title: '產品編號' 60}, { 61field: 'CustName', 62title: '客戶姓名' 63}, { 64field: 'CustAddress', 65title: '客戶地址', 66}, { 67field: 'CustPhone', 68title: '客戶電話', 69}, { 70field: 'CustCompany', 71title: '客戶公司', 72}, { 73field: 'CreateDateTime', 74title: '訂單建立時間', 75}, { 76field: 'UpdateDateTime', 77title: '訂單更新時間', 78}] 79}); 80return InitTable; 81 }; View Code
2.訂單表增刪改查
1 $(function () { 2//初始時間控制元件 3var frstDayDate = GetLocalMonFrstDayDate(); 4var lastDayDate = GetLocalMonLastDayDate(); 5$("#startDate").val(frstDayDate); 6$("#endDate").val(lastDayDate); 7 8//初始化bootstrap-table引數 9var filterParam = ""; 10var startDate = $("#startDate").val(); 11var endDate = $("#endDate").val(); 12url = "/SaleManage/GetOrderList?startDate=" + startDate + "&endDate=" + endDate + "&orderNO=" + filterParam + ""; 13InitTable(url); 14 15//查詢資料 16$("#btn_query").click(function () { 17var filterParam = $("#queryKey").val(); 18var startDate = $("#startDate").val(); 19var endDate = $("#endDate").val(); 20var url = "/SaleManage/GetOrderList?startDate="+ startDate + "&endDate=" +endDate + "&orderNO=" + filterParam + ""; 21InitTable(url); 22}) 23 24//新增 25$("#btn_add").click(function () { 26var url = "/SaleManage/AddForm"; 27openDialog(url, "AddForm", "新增訂單", 645, 470, function (iframe) { 28top.frames[iframe].AcceptClick() 29}); 30}) 31 32//編輯 33$("#btn_edit").click(function () { 34//獲取當前選擇行id 35var selectedRows = $("#tb_SaleOrder").bootstrapTable('getSelections'); 36if (selectedRows.length <= 0) { 37alert('請選擇要編輯的資料'); 38} else if (selectedRows.length > 1) { 39alert('一次只能選擇一行資料進行編輯'); 40} else { 41var KeyValue = selectedRows[0].OrderNO; 42var url = "/SaleManage/EditForm?KeyValue=" + KeyValue; 43openDialog(url, "EditForm", "編輯郵件", 645, 470, function (iframe) { 44top.frames[iframe].AcceptClick() 45}); 46} 47}) 48//刪除資料 49$("#btn_delete").click(function () { 50//獲取當前選擇行id 51var selectedRows = $("#tb_SaleOrder").bootstrapTable('getSelections'); 52if (selectedRows.length <= 0) { 53alert('請選擇要刪除的資料'); 54return; 55} 56if (selectedRows.length > 1) { 57alert('一次只能選擇一行刪除'); 58return; 59} 60var orderNo = selectedRows[0].OrderNO; 61//aja非同步請求 62$.ajax({ 63url: '/SaleManage/DelOrder', 64type: 'get', 65contentType: 'application/json;charset=utf-8', 66data: { orderNo: orderNo }, 67success: function (data) { 68//重新整理bootstrap-table 69$("#tb_SaleOrder").bootstrapTable('refresh'); 70}, 71error: function (data) { 72alert('資料刪除失敗' + data); 73} 74}) 75}) 76 77//回車鍵 78document.onkeydown = function (e) { 79if (!e) e = window.event; //火狐中是 window.event 80if ((e.keyCode || e.which) == 13) { 81var query = document.getElementById("btn_query"); 82query.focus(); 83query.click(); 84} 85} 86 }); View Code
3.日期初始化
1 //當月第一天所對應的日期 yyyy-mm-dd 2 function GetLocalMonFrstDayDate() { 3var now = new Date(); 4var year = now.getFullYear();//年 5var mon = now.getMonth() + 1;//月 6if (mon < 10) { 7mon = '-0' + mon; 8} 9var frstDay = "-01"; //日 10return year + mon + frstDay; 11 } 12 //當月最後一天所對應的日期 yyyy-mm-dd 13 function GetLocalMonLastDayDate() { 14var now = new Date(); 15var year = now.getFullYear();//年 16var mon = now.getMonth() + 1;//月 17if (mon < 10) { 18mon = '-0' + mon; 19} 20var LastDay = "-" + GetDayCountInMon(year + mon); 21return year + mon + LastDay; 22 } 23 //計算當月對應的最大天數 24 function GetDayCountInMon(YearMon) { 25var arr = YearMon.split("-"); 26var localYear = parseInt(arr[0]); 27var localMon = parseInt(arr[1]); 28var localDate = new Date(localYear, localMon, 0); 29return localDate.getDate(); 30 } View Code
4.Index.cshtml
1 @{ 2Layout = "~/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訂單編號:<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 { 35background-color: #449d44; 36} 37 38#tb_SaleOrder > thead th { 39padding: 0; 40margin: 0; 41background-color: #d9edf7; 42} 43 </style> 44 <script> 45//重新整理bootstrap-table 46function refleshBootStrapTable() { 47$("#tb_SaleOrder").bootstrapTable('refresh'); 48} 49 </script> 50 51 <script src="~/CustomUI/TableJS/SaleOrder.js"></script> View Code
5.AddForm.cshtml
1 @{ 2ViewBag.Title = "AddForm"; 3Layout = "~/Views/Shared/_LayoutBTSTable.cshtml"; 4 } 5 6 <script> 7//新增資料 8function AcceptClick() { 9var OrderNO = $("#OrderNO").val(); 10var ProductNo = $("#ProductNo").val(); 11var CustName = $("#CustName").val(); 12var CustAddress = $("#CustAddress").val(); 13var CustPhone = $("#CustPhone").val(); 14var CustCompany = $("#CustCompany").val(); 15var CreateDateTime = $("#CreateDateTime").val(); 16var UpdateDateTime = $("#UpdateDateTime").val(); 17$.ajax({ 18url: '/SaleManage/AddDataToDB', 19type: 'get', 20contentType: 'application/json;charset=utf-8', 21data: { 22'OrderNO': OrderNO, 'ProductNo': ProductNo, 'CustName': CustName, 23'CustAddress': CustAddress, 'CustPhone': CustPhone, 'CustCompany': CustCompany, 24'CreateDateTime': CreateDateTime, 'UpdateDateTime': UpdateDateTime 25}, 26success: function (data) { 27reflesh(); 28//關閉對話方塊 29closeDialog(); 30}, 31error: function (data) { 32alert('新增資料失敗' + data); 33} 34}) 35} 36//重新整理 37function reflesh() { 38window.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">訂單編號:</td> 47<td><input type="text" id="OrderNO" style="width:500px;" /></td> 48</tr> 49<tr> 50<td style="height:35px;line-height:35px">產品名稱:</td> 51<td><input type="text" id="ProductNo" style="width:500px;" /></td> 52</tr> 53<tr> 54<td style="height:35px;line-height:35px">客戶姓名:</td> 55<td><input type="text" id="CustName" style="width:500px;" /></td> 56</tr> 57<tr> 58<td style="height:35px;line-height:35px">客戶地址:</td> 59<td><input type="text" id="CustAddress" style="width:500px;" /></td> 60</tr> 61<tr> 62<td style="height:35px;line-height:35px">客戶電話:</td> 63<td><input type="text" id="CustPhone" style="width:500px;" /></td> 64</tr> 65<tr> 66<td style="height:35px;line-height:35px">客戶公司:</td> 67<td><input type="text" id="CustCompany" style="width:500px;" /></td> 68</tr> 69<tr> 70<td style="height:35px;line-height:35px">訂單建立時間:</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">訂單更新時間:</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] { 82height: 35px; 83border-radius: 6px; 84border: 1px #cccccc solid; 85outline: 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">訂單編號:</td> <td><input type="text" id="OrderNO" style="width:500px;" disabled/></td> </tr> <tr> <td style="height:35px;line-height:35px">產品名稱:</td> <td><input type="text" id="ProductNo" style="width:500px;" /></td> </tr> <tr> <td style="height:35px;line-height:35px">客戶姓名:</td> <td><input type="text" id="CustName" style="width:500px;" /></td> </tr> <tr> <td style="height:35px;line-height:35px">客戶地址:</td> <td><input type="text" id="CustAddress" style="width:500px;" /></td> </tr> <tr> <td style="height:35px;line-height:35px">客戶電話:</td> <td><input type="text" id="CustPhone" style="width:500px;" /></td> </tr> <tr> <td style="height:35px;line-height:35px">客戶公司:</td> <td><input type="text" id="CustCompany" style="width:500px;" /></td> </tr> <tr> <td style="height:35px;line-height:35px">訂單建立時間:</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">訂單更新時間:</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 @{ 2ViewBag.Title = "EditForm"; 3Layout = "~/Views/Shared/_LayoutBTSTable.cshtml"; 4 } 5 6 <script> 7$(function () { 8//初始化頁面控制元件 9$.ajax({ 10url: "/SaleManage/InitModifySheet", 11type: 'get', 12contentType: 'application/json;charset=utf-8', 13data: { 14orderNO: GetQuery('KeyValue') 15}, 16success: function (data) { 17//將回調資料轉化為json物件 18var 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}, 29error: function (data) { 30alert('編輯資料失敗' + data); 31} 32}) 33}) 34 35//新增資料 36function AcceptClick() { 37var OrderNO = $("#OrderNO").val(); 38var ProductNo = $("#ProductNo").val(); 39var CustName = $("#CustName").val(); 40var CustAddress = $("#CustAddress").val(); 41var CustPhone = $("#CustPhone").val(); 42var CustCompany = $("#CustCompany").val(); 43var CreateDateTime = $("#CreateDateTime").val(); 44var UpdateDateTime = $("#UpdateDateTime").val(); 45$.ajax({ 46url: '/SaleManage/ModifyDataToDB', 47type: 'get', 48contentType: 'application/json;charset=utf-8', 49data: { 50'OrderNO': OrderNO, 'ProductNo': ProductNo, 'CustName': CustName, 51'CustAddress': CustAddress, 'CustPhone': CustPhone, 'CustCompany': CustCompany, 52'CreateDateTime': CreateDateTime, 'UpdateDateTime': UpdateDateTime 53}, 54success: function (data) { 55reflesh(); 56//關閉對話方塊 57closeDialog(); 58}, 59error: function (data) { 60alert('新增資料失敗' + data); 61} 62}) 63} 64//重新整理 65function reflesh() { 66window.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">訂單編號:</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">產品名稱:</td> 80<td><input type="text" id="ProductNo" style="width:500px;" /></td> 81</tr> 82<tr> 83<td style="height:35px;line-height:35px">客戶姓名:</td> 84<td><input type="text" id="CustName" style="width:500px;" /></td> 85</tr> 86<tr> 87<td style="height:35px;line-height:35px">客戶地址:</td> 88<td><input type="text" id="CustAddress" style="width:500px;" /></td> 89</tr> 90<tr> 91<td style="height:35px;line-height:35px">客戶電話:</td> 92<td><input type="text" id="CustPhone" style="width:500px;" /></td> 93</tr> 94<tr> 95<td style="height:35px;line-height:35px">客戶公司:</td> 96<td><input type="text" id="CustCompany" style="width:500px;" /></td> 97</tr> 98<tr> 99<td style="height:35px;line-height:35px">訂單建立時間:</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">訂單更新時間:</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] { 111height: 35px; 112border-radius: 6px; 113border: 1px #cccccc solid; 114outline: none 115} 116 </style> View Code
8.ParentAndChild.cshtml
1 @{ 2Layout = "~/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訂單編號:<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 { 35padding: 0; 36margin: 0; 37background-color: #d9edf7; 38} 39 </style> 40 <script> 41//重新整理bootstrap-table 42function 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 { 13public class ImportExcelToDB 14{ 15//全域性資料庫連線字串 16private readonly string strConnection = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString; 17 18//從Excel讀取資料 19public static DataSet ReadExcelDataToTable(string filepath) 20{ 21try 22{ 23int index1 = filepath.LastIndexOf("\\"); 24int index2 = filepath.LastIndexOf("."); 25string fileName ="["+filepath.Substring(index1+1,index2-index1-1)+"$]"; 26string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", filepath); 27using (OleDbConnection oleConn = new OleDbConnection(strConn)) 28{ 29oleConn.Open(); 30string sql = "select * from "+fileName+ ""; 31OleDbDataAdapter oleDaExcel = new OleDbDataAdapter(sql, oleConn); 32DataSet oleDsExcel = new DataSet(); 33oleDaExcel.Fill(oleDsExcel, "table1"); 34return oleDsExcel; 35} 36} 37catch (Exception ex) 38{ 39throw ex; 40} 41} 42public void InsertExcelDataToDB(string fileName) 43{ 44//匯入表格格式化SQL 45string sqlText = @"INSERT INTO [dbo].[SaleOrder] 46([OrderNO] 47,[ProductNo] 48,[CustName] 49,[CustAddress] 50,[CustPhone] 51,[CustCompany] 52,[CreateDateTime] 53,[UpDateDateTime]) 54VALUES 55('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')"; 56 57if (!System.IO.File.Exists(fileName)) 58{ 59throw new Exception("指定路徑的Excel檔案不存在!"); 60} 61DataSet ds = ReadExcelDataToTable(fileName); 62DataTable dt = ds.Tables[0]; 63//將excel資料插入到DB之前,先判斷DB中是否存在資料 64DelDBRepeatData(dt); 65List<string> list = (from DataRow row in dt.Rows 66select String.Format(sqlText, row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7])).ToList(); 67OperateDB(list); 68} 69 70/* 71將excel資料插入到DB之前, 72先判斷DB中是否存在同一天同一員工記錄 73*/ 74public int DelDBRepeatData(DataTable dt) 75{ 76//sql指令碼 77string delSqlText = @"DELETE FROM [dbo].[SaleOrder] 78WHERE OrderNO IN ('{0}') 79"; 80 81//取excel中的員工號和打卡日期 82StringBuilder strBld = new StringBuilder(); 83 84for (int i = 0; i < dt.Rows.Count; i++) 85{ 86strBld.Append(dt.Rows[i][0]); 87 88} 89 90List<string> list = (from DataRow row in dt.Rows 91select String.Format(delSqlText, row[0])).ToList(); 92 93OperateDB(list); 94return 0; 95} 96 97//DB操作 98public int OperateDB(List<string> list) 99{ 100int result = 0; 101using (SqlConnection conn = new SqlConnection(strConnection)) 102{ 103if (conn.State==ConnectionState.Closed) 104{ 105conn.Open(); 106} 107foreach (string item in list) 108{ 109SqlCommand cmd = new SqlCommand(item, conn); 110result=cmd.ExecuteNonQuery(); 111} 112} 113return 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> 14public static class JsonHelper 15{ 16public static object ToJson(this string Json) 17{ 18return JsonConvert.DeserializeObject(Json); 19} 20public static string ToJson(this object obj) 21{ 22return JsonConvert.SerializeObject(obj); 23} 24public static List<T> JonsToList<T>(this string Json) 25{ 26return JsonConvert.DeserializeObject<List<T>>(Json); 27} 28public static T JsonToEntity<T>(this string Json) 29{ 30return 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//銷售管理 14public class SaleManageController : BaseManageController 15{ 16ImportExcelToDB ImportToExcl = new ImportExcelToDB(); 17SaleOrderBLL SOBLL = new SaleOrderBLL(); 18SaleProductBLL SPBLL = new SaleProductBLL(); 19public override ActionResult Index() 20{ 21return View(); 22} 23//匯入頁面 24public ActionResult Import() 25{ 26return View(); 27} 28 29//將Excel訂單資料匯入 30[HttpPost] 31public ActionResult ImportExclToDB(HttpPostedFileBase file) 32{ 33var severPath = this.Server.MapPath("/Files"); //獲取當前虛擬檔案路徑 34var savePath = Path.Combine(severPath, file.FileName); //拼接儲存檔案路徑 35file.SaveAs(savePath); 36try 37{ 38ImportToExcl.InsertExcelDataToDB(savePath); 39return Content("<script>alert('上傳成功!!')</script>"); 40} 41catch (Exception ex) 42{ 43throw new Exception(ex.Message); 44} 45 46//Response.Redirect("/PunchCardRecord/Index"); 47} 48 49//父子頁面 50public ActionResult ParentAndChild() 51{ 52return View(); 53} 54 55//獲取子表資料 56public ActionResult GetChildDataList(int limit, int offset,string productNo) 57{ 58List<SaleProduct> list = SPBLL.GetProductOrderList(productNo); 59int total = list.Count; 60var rows = list.Skip(offset).Take(limit).ToList(); 61return Json(new { total, rows }, JsonRequestBehavior.AllowGet); 62} 63 64//獲取訂單列表 65public ActionResult GetOrderList(int limit, int offset,string startDate,string endDate,string orderNO) 66{ 67List<SaleOrder> list = SOBLL.GetSaleOrderList(startDate,endDate, orderNO); 68int total = list.Count; 69var rows = list.Skip(offset).Take(limit).ToList(); 70return Json(new { total, rows }, JsonRequestBehavior.AllowGet); 71} 72//刪除資料 73public void DelOrder(string orderNo) 74{ 75SOBLL.DelDataToDB(orderNo); 76} 77//新增資料 78public void AddDataToDB(SaleOrder saleOrder) 79{ 80SOBLL.AddDataToDB(saleOrder); 81} 82//初始化修改表單 83public ActionResult InitModifySheet(string orderNO) 84{ 85List<SaleOrder> list = SOBLL.GetSaleOrderList("", "", orderNO); 86return Content(list.ToJson()); 87} 88//修改資料 89public void ModifyDataToDB(SaleOrder saleOrder) 90{ 91SOBLL.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({ 7rowStyle: function (row, index) {//row 表示行資料,object,index為行索引,從0開始 8var style = ""; 9if (row.SignInTime == '' || row.SignOutTime == '') { 10style = { css: { 'color': 'red' } }; 11} 12return style; 13}, 14//searchAlign: 'left', 15//search: true,//顯示隱藏搜尋框 16showHeader: true,//是否顯示列頭 17//classes: 'table-no-bordered', 18showLoading: true, 19undefinedText: '', 20showFullscreen: true, 21toolbarAlign: 'left', 22paginationHAlign: 'right', 23silent: true, 24url: url, 25method: 'get',//請求方式(*) 26toolbar: '#toolbar',//工具按鈕用哪個容器 27striped: true,//是否顯示行間隔色 28cache: false,//是否使用快取,預設為true,所以一般情況下需要設定一下這個屬性(*) 29pagination: true,//是否顯示分頁(*) 30sortable: false,//是否啟用排序 31sortOrder: "asc",//排序方式 32//queryParams: InitTable.queryParams,//傳遞引數(*) 33sidePagination: "server",//分頁方式:client客戶端分頁,server服務端分頁(*) 34pageNumber: 1,//初始化載入第一頁,預設第一頁 35pageSize: 10,//每頁的記錄行數(*) 36pageList: [2, 5, 10, 15],//可供選擇的每頁的行數(*) 37search: false,//是否顯示錶格搜尋,此搜尋是客戶端搜尋,不會進服務端,所以,個人感覺意義不大 38strictSearch: true, 39showColumns: true,//是否顯示所有的列 40showRefresh: true,//是否顯示重新整理按鈕 41minimumCountColumns: 2,//最少允許的列數 42clickToSelect: true,//是否啟用點選選中行 43//height: 680,//行高,如果沒有設定height屬性,表格自動根據記錄條數覺得表格高度 44uniqueId: "ID",//每一行的唯一標識,一般為主鍵列 45showToggle: true,//是否顯示詳細檢視和列表檢視的切換按鈕 46cardView: false,//是否顯示詳細檢視 47detailView: true,//是否顯示父子表 48showExport: true, 49//exportDataType: 'all', 50exportDataType: "selected",//匯出checkbox選中的行數 51paginationLoop: false,//是否無限迴圈 52columns: [{ 53checkbox: true 54}, { 55field: 'OrderNO', 56title: '訂單編號' 57}, { 58field: 'ProductNo', 59title: '產品編號' 60}, { 61field: 'CustName', 62title: '客戶姓名' 63}, { 64field: 'CustAddress', 65title: '客戶地址', 66}, { 67field: 'CustPhone', 68title: '客戶電話', 69}, { 70field: 'CustCompany', 71title: '客戶公司', 72}, { 73field: 'CreateDateTime', 74title: '訂單建立時間', 75}, { 76field: 'UpdateDateTime', 77title: '訂單更新時間', 78}], 79 80//無限迴圈取子表,直到子表裡面沒有記錄 81onExpandRow: function (index, row, $Subdetail) { 82InitSubTable(index, row, $Subdetail); 83} 84}); 85return InitTable; 86 87 88 }; 89 90 //初始化子表格(無線迴圈) 91 InitSubTable = function (index, row, $detail) { 92var parentid = row.ProductNo; 93var cur_table = $detail.html('<table></table>').find('table'); 94$(cur_table).bootstrapTable({ 95url: "/SaleManage/GetChildDataList", 96method: 'get', 97queryParams: { 'limit':10000,'offset':0,'productNo':parentid}, 98clickToSelect: true, 99detailView: false,//父子表 100sidePagination: "server", 101uniqueId: "ProductNo", 102pageSize: 10, 103pageList: [10, 25], 104columns: [{ 105field: 'ProductNo', 106title: '產品編號' 107}, 108{ 109field: 'ProductName', 110title: '產品名稱' 111}, { 112field: 'ProductType', 113title: '產品型別' 114}, { 115field: 'ProductCount', 116title: '產品數量' 117}, 118{ 119field: 'ProductPrice', 120title: '產品單價' 121}], 122//無限迴圈取子表,直到子表裡面沒有記錄 123onExpandRow: function (index, row, $Subdetail) { 124InitSubTable(index, row, $Subdetail); 125} 126}); 127 }; View Code
(三)其他技術點
1.改變bootstrap-table表頭顏色
1 #tb_SaleOrder > thead th { 2padding: 0; 3margin: 0; 4background-color: #d9edf7; 5}
2.改變bootstrap-table 游標懸停顏色
1 #tb_SaleOrder tbody > tr:hover { 2background-color: #449d44; 3}
3.重新整理bootstrap-table
1 //重新整理bootstrap-table 2function refleshBootStrapTable() { 3$("#tb_SaleOrder").bootstrapTable('refresh'); 4}
4.彈窗
1 /* 2 彈出對話方塊(帶:確認按鈕、取消按鈕) 3 */ 4 function openDialog(url, _id, _title, _width, _height, callBack) { 5Loading(true); 6top.$.dialog({ 7id: _id, 8width: _width, 9height: _height, 10max: false, 11lock: true, 12title: _title, 13resize: false, 14extendDrag: true, 15content: 'url:' + RootPath() + url, 16ok: function () { 17callBack(_id); 18return false; 19}, 20cancel: true 21}); 22 }
5.Bootstrap-table核心技術點,再次強調
1 var InitTable = function (url) { 2//先銷燬表格 3$('#tb_SaleOrder').bootstrapTable("destroy"); 4//載入表格 5$('#tb_SaleOrder').bootstrapTable({ 6rowStyle: function (row, index) {//row 表示行資料,object,index為行索引,從0開始 7var style = ""; 8if (row.SignInTime == '' || row.SignOutTime=='') { 9style = { css: { 'color': 'red' } }; 10} 11returnstyle; 12}, 13//searchAlign: 'left', 14//search: true,//顯示隱藏搜尋框 15showHeader: true,//是否顯示列頭 16//classes: 'table-no-bordered', 17showLoading: true, 18undefinedText: '', 19showFullscreen: true, 20toolbarAlign: 'left', 21paginationHAlign: 'right', 22silent: true, 23url: url, 24method: 'get',//請求方式(*) 25toolbar: '#toolbar',//工具按鈕用哪個容器 26striped: true,//是否顯示行間隔色 27cache: false,//是否使用快取,預設為true,所以一般情況下需要設定一下這個屬性(*) 28pagination: true,//是否顯示分頁(*) 29sortable: false,//是否啟用排序 30sortOrder: "asc",//排序方式 31//queryParams: InitTable.queryParams,//傳遞引數(*) 32sidePagination: "server",//分頁方式:client客戶端分頁,server服務端分頁(*) 33pageNumber: 1,//初始化載入第一頁,預設第一頁 34pageSize: 10,//每頁的記錄行數(*) 35pageList: [2, 5, 10, 15],//可供選擇的每頁的行數(*) 36search: false,//是否顯示錶格搜尋,此搜尋是客戶端搜尋,不會進服務端,所以,個人感覺意義不大 37strictSearch: true, 38showColumns: true,//是否顯示所有的列 39showRefresh: true,//是否顯示重新整理按鈕 40minimumCountColumns: 2,//最少允許的列數 41clickToSelect: true,//是否啟用點選選中行 42//height: 680,//行高,如果沒有設定height屬性,表格自動根據記錄條數覺得表格高度 43uniqueId: "ID",//每一行的唯一標識,一般為主鍵列 44showToggle: true,//是否顯示詳細檢視和列表檢視的切換按鈕 45cardView: false,//是否顯示詳細檢視 46detailView: false,//是否顯示父子表 47showExport: true, 48//exportDataType: 'all', 49exportDataType: "selected",//匯出checkbox選中的行數 50paginationLoop: false,//是否無限迴圈 51columns: [{ 52checkbox: true 53}, { 54field: 'OrderNO', 55title: '訂單編號' 56}, { 57field: 'ProductNo', 58title: '產品編號' 59}, { 60field: 'CustName', 61title: '客戶姓名' 62}, { 63field: 'CustAddress', 64title: '客戶地址', 65}, { 66field: 'CustPhone', 67title: '客戶電話', 68}, { 69field: 'CustCompany', 70title: '客戶公司', 71}, { 72field: 'CreateDateTime', 73title: '訂單建立時間', 74}, { 75field: 'UpdateDateTime', 76title: '訂單更新時間', 77}] 78}); 79return InitTable; 80 };
四 寫在最後
本片文章藉助於bootstrap-table外掛,實現了基本的增刪改查,匯入匯出,分頁,父子表等。至於其他技術,如凍結表頭,列排列,行拖動,列拖動等,會在後續文章中與大家分享。