[英]ASP.NET MVC DataTable sum column
我需要對“總計”列求和。 我想將結果添加到表格的頁腳。
<script>
$(document).ready(function () {
$("#orderTable").DataTable(
{
"ajax": {
"url": "/Orders/GetList",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "CustomerName" },
{ "data": "OrderDate" },
{ "data": "Total" },
]
});
});
</script>
任何指導表示贊賞。
對於其他正在尋找解決方案的人:
<script>
$(document).ready(function () {
$("#orderTable").DataTable(
{
"ajax": {
"url": "/Orders/GetList",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "CustomerName" },
{ "data": "OrderDate" },
{ "data": "Total" },
],
footerCallback: function (row, data, start, end, display) {
var api = this.api(), data;
// Remove the formatting to get integer data for summation
var intVal = function (i) {
return typeof i === 'string' ? i.replace(/[\$,]/g, '') * 1 : typeof i === 'number' ? i : 0;
};
// Total over this page
data = api.column(2, {
page: 'current'
}).data(); pageTotal = data.length ? data.reduce(function (a, b) { return intVal(a) + intVal(b); }) : 0;
// Update footer
$(api.column(2).footer()).html('$' + pageTotal);
}
});
});
</script>
ref: Jquery DataTable column Sum (第二個答案中的良好結構參考)
參考: https : //www.ihbc.org.uk/consultationsdb_new/examples/advanced_init/footer_callback.html
有一個名為drawCallback
選項,使用如下所示。
drawCallback: function () {
var yourSum = $('#orderTable').DataTable().column(number).data().sum(); // column number just like 1 , 2, 3, 4 ............... which you try to add
$('#total').html(sum); // #total is your html element id
}
和 HTML 總計:
<div id="total"></div>
通過 CSS 將您的div
放置在您想要的任何位置。
我認為最好的辦法是直接從服務器獲取總和,例如 ("/Orders/GetTotal") 您可以一起處理 GetTotal 和 GetList 以防止對數據庫的雙重請求
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.