筆記如何在系統專案中使用 DataTables 元件


  1. 說明
    1. 安裝方式
    2. 引用方式

系統專案的開發經常會有對表格篩選、排序、分頁的功能,藉由使用 DataTables 前端元件就能夠快速解決這個需求。

logo

說明

安裝方式

Visual Studio 使用 libman 安裝

"libraries": [
  {
    "library": "datatables.net-bs4@1.10.24",
    "destination": "lib/datatables.net-bs4/",
    "files": [
      "dataTables.bootstrap4.min.js",
      "dataTables.bootstrap4.min.css"
    ]
  },
  {
    "library": "datatables@1.10.21",
    "destination": "lib/datatables/",
    "files": [
      "js/jquery.dataTables.min.js"
    ]
  }
]

引用方式

在要使用的 View Include 相關的 js script,並且要根據 Table 的 ID 進行 init DataTables

@section scripts{
  <script src="~/lib/datatables/js/jquery.dataTables.min.js"></script>
  <script src="~/lib/datatables.net-bs4/dataTables.bootstrap4.min.js"></script>
  <script>
      $(document).ready(function () {

          $('#tableId').DataTable({
              "searching": true,
              "pageLength": 50,
              "bLengthChange": false,
              "order": [[ 0, "desc" ]], // Default Order
              "columnDefs": [
                  { "targets": 0, "orderable": true },
                  { "targets": 1, "orderable": false },
                  { "targets": 1, "searchable": false },
              ],
              "language": {
                  "lengthMenu": "Display _MENU_ records per page",
                  "zeroRecords": "沒有任何查詢結果,請調整搜尋條件後再執行。",
                  "info": "搜尋共有 _TOTAL_ 個項目",
                  "infoEmpty": "",
                  "infoFiltered": "(filtered from _MAX_ total records)"
              }
          });
      });
  </script>
}

此外 language 也可以用外指 JS files 的方式設定:

"language": {
    "url": "@Url.Content("~/Scripts/DataTables/traditional-chinese.json")"
},
{
	"processing":   "處理中...",
	"loadingRecords": "載入中...",
	"lengthMenu":   "顯示 _MENU_ 項結果",
	"zeroRecords":  "沒有符合的結果",
	"info":         "顯示第 _START_ 至 _END_ 項結果,共 _TOTAL_ 項",
	"infoEmpty":    "顯示第 0 至 0 項結果,共 0 項",
	"infoFiltered": "(從 _MAX_ 項結果中過濾)",
	"infoPostFix":  "",
	"search":       "搜尋:",
	"paginate": {
		"first":    "第一頁",
		"previous": "上一頁",
		"next":     "下一頁",
		"last":     "最後一頁"
	},
	"aria": {
		"sortAscending":  ": 升冪排列",
		"sortDescending": ": 降冪排列"
	}
}

Table 的使用要注意必須包含 TheadTbody 才能正確解析。

<table class="table table-bordered table-striped" id="EmpTable">
    <thead>
      <tr>
        <th>標頭</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>資料</td>
      </tr>
    </tbody>
</table>