ASP.NET Core 6 Web应用中如何展示Price列的总计值
实现ASP.NET Core 6 Razor Pages中DataTable的Price列总计展示
我基于ASP.NET Core 6搭建Web应用,采用Razor Pages模式,通过Index.cshtml页面与Data.js文件获取数据并加载到DataTable中,目前数据已成功加载,需要实现展示Price列的总计值。
现有代码
Index.cshtml 标记与脚本
<div class="x_content"> <table class="table table-hover" id="tblProduct"> <thead> <tr> <th>#</th> <th>Name</th> <th>Category</th> <th>Price</th> </tr> </thead> <tbody></tbody> <tfoot> <tr> <th>Sum:</th> <th></th> </tr> </tfoot> </table> </div> <script type="text/javascript"> var js = jQuery.noConflict(true); js('#tblProduct').dataTable({ "footerCallback": function (row, data, start, end, display) { var api = this.api(), data; var intVal = function (i) { return typeof i === 'string' ? i.replace(/[\$a-zA-Z, ]/g, '') * 1 : typeof i === 'number' ? i : 0; }; var cols = [1]; for (let index = 0; index < cols.length; index++) { var col_data = cols[index]; total = api .column(col_data) .data() .reduce(function (a, b) { return intVal(a) + intVal(b); }, 0); // Update footer js(api.column(col_data).footer()).html( total ); } } }); </script>
Data.js 加载代码
function BindProductsToGrid(products) { $('#tblProduct tbody').empty(); var tr; $.each(products, function (index, product) { tr = $('<tr/>'); tr.append(`<td>${(index + 1)}</td>`); tr.append(`<td>${product.name}</td>`); tr.append(`<td>${product.category}</td>`); tr.append(`<td>${product.price}</td>`); $('#tblProduct').append(tr); }); }
当前数据展示效果

修改方案
要实现Price列的总计,需要调整两处:
- 修正表格页脚的列结构:当前
tfoot的<tr>只有2个<th>,需要和表头列数保持一致(4列),让总计值对应到Price列的位置:
<tfoot> <tr> <th>Sum:</th> <th></th> <th></th> <th></th> </tr> </tfoot>
- 调整DataTable脚注回调的目标列:DataTable的列索引从0开始,Price列是第4列(索引为3),同时当前代码中
cols数组指定的是索引1(Name列),需要修改为索引3:
var cols = [3];
修改后的完整脚本部分:
var js = jQuery.noConflict(true); js('#tblProduct').dataTable({ "footerCallback": function (row, data, start, end, display) { var api = this.api(); var intVal = function (i) { return typeof i === 'string' ? i.replace(/[\$a-zA-Z, ]/g, '') * 1 : typeof i === 'number' ? i : 0; }; var cols = [3]; for (let index = 0; index < cols.length; index++) { var col_data = cols[index]; total = api .column(col_data) .data() .reduce(function (a, b) { return intVal(a) + intVal(b); }, 0); // Update footer js(api.column(col_data).footer()).html(total); } } });
这样修改后,DataTable会自动计算Price列的所有值的总和,并显示在页脚对应的位置。
内容的提问来源于stack exchange,提问作者ndn
相关产品推荐
相关产品推荐

