【问题标题】:How to grab the sum of a jquery datatables column to use in aspx?如何获取要在 aspx 中使用的 jquery 数据表列的总和?
【发布时间】:2020-09-11 08:14:36
【问题描述】:

我在代码隐藏 .cs 文件中生成数据表的代码。我有一些带有货币值的列。如何对整列求和并抓取它,以便在 .cs 文件中使用它来填充标签?

如果使用搜索过滤器,是否也可以只获取显示结果的值?例如。在搜索过滤器中输入了一些内容,因此行被隐藏,我只需要可见行的总和。

谢谢

aspx:

<div id="DIV_Table" runat="server"> </div> //the content will be filled code-behind
<asp:Label ID="lbl_Sum" runat="server"></asp:Label> //Label to show the sum

cs:

//datatable dt is the source
string html = "<table id='liste' class='display' cellspacing='0' style='width:100%'><thead>";
        //add header row
        html += "<tr>";

        for (int i = 0; i <= dt.Columns.Count - 1; i++)
        {
            html += "<th>" + dt.Columns[i].ColumnName + "</th>";
        }
        html += "</tr></thead><tbody>";

        //add rows
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            html += "<tr>";
        for (int y = 0; y <= dt.Columns.Count - 1; y++)
            {
            html += "<td>" + dt.Rows[i][y].ToString() + "</td>";
            }
            html += "</tr>";
          }

        //footer
        html += "</tbody><tfoot><tr>";
        foreach (DataColumn dc in dt.Columns) html += @"<th>" + dc.ColumnName + "</th>";
        html += "</tr></tfoot></table>";

        //javascript
        html += @"<script>
        $(document).ready(function() {

                      $('#liste').DataTable({                                    
                                fixedHeader: {
                                                header: true,
                                                footer: true
                                            },
                                
                                order: [[ 0, 'desc' ]],

                                paging: false,

                                columnDefs: [{ type: 'currency', targets: 7 }
                                             { targets: 8, visible: false},],

                                language: { 'decimal': ',',
                                            'thousands': '.',
                                            'sEmptyTable': 'Keine Daten in der Tabelle vorhanden',
                                            'sInfo': '_START_ bis _END_ von _TOTAL_ Einträgen',
                                            'sInfoEmpty': '0 bis 0 von 0 Einträgen',
                                            'sInfoFiltered': '(gefiltert von _MAX_ Einträgen)',
                                            'sInfoPostFix': '',
                                            'sInfoThousands': '.',
                                            'sLengthMenu': '_MENU_ Einträge anzeigen',
                                            'sLoadingRecords': 'Wird geladen...',
                                            'sProcessing': 'Bitte warten...',
                                            'sSearch': 'Suchen',
                                            'sZeroRecords': 'Keine Einträge vorhanden.',
                                            'oPaginate': {
                                            'sFirst': 'Erste',
                                            'sPrevious': 'Zurück',
                                            'sNext': 'Nächste',
                                            'sLast': 'Letzte'
                                            },
                                            'oAria': {
                                            'sSortAscending': ': aktivieren, um Spalte aufsteigend zu sortieren',
                                            'sSortDescending': ': aktivieren, um Spalte absteigend zu sortieren'
                                            }
                                         }, 
                            
                                        rowCallback: function(row, data, index)
                                        {
                                            if(data[29] == 'Abgeschlossen') { $(row).css('background-color', '#bfbfbf'); }
                                        },

                          });
                    });
                   </script>";

DIV_Table.InnerHtml = html;

【问题讨论】:

  • 您能否添加您从代码隐藏中为数据表生成的 C# 代码?也可以加上你要填写的标签吗?
  • 好吧,既然您正在循环访问您的数据(在//add rows 下),您可以创建一个变量来存储货币总额。每当它所在的列位置出现时,只需添加它。然后在循环之后设置该标签值:lbl_Sum.Text = total.ToString("c");。为了在有人搜索时更新标签值...您可能必须使用数据表搜索事件,然后使用行 API .rows( { page: 'current' } ) 获取可见行的数据以获取行数据,然后将列与货币相加并更新标签。
  • 我还建议将您的 HTML 与您的代码隐藏分开。就像使用 &lt;asp:Repeater /&gt; 在您的 aspx 页面上创建表格行一样。在 aspx 页面中管理 HTML 代码比在隐藏文件中的 cs 代码中容易得多。与 javascript 相同
  • @zgood 感谢 cmets。循环的好主意,我会这样做。你能告诉我如何通过 API 获取行的值,以便我可以在代码隐藏中使用它吗?那就是我卡住的地方。也感谢Repeater 的提示,我会看看
  • 我可以使用数据表的sum() 函数,如示例中的:datatables.net/examples/plug-ins/api 但是如何将结果返回给我的 aspx 标签?

标签: asp.net datatables sum


【解决方案1】:

将更改您当前的大部分代码,您可以通过在数据表search.dt 事件上运行.sum() 数据表函数you linked 来调整它,然后在页面加载时运行它以获取初始值。见下文(只有 javascript 对您很重要 - HTML 和 CSS 仅用于演示。通过搜索字母“c”或字母“f”来查看基于第 8 列值的总变化):

var table;
$(document).ready(function() {

  $.fn.dataTable.Api.register('column().data().sum()', function() {
    return this.reduce(function(a, b) {
      var x = parseFloat(a) || 0;
      var y = parseFloat(b) || 0;
      return x + y;
    });
  });

  table = $('#liste').DataTable({
      fixedHeader: {
        header: true,
        footer: true
      },

      order: [
        [0, 'desc']
      ],

      paging: false,

      columnDefs: [{
        type: 'currency',
        targets: 7
      }, {
        targets: 8,
        visible: false
      }],

      language: {
        'decimal': ',',
        'thousands': '.',
        'sEmptyTable': 'Keine Daten in der Tabelle vorhanden',
        'sInfo': '_START_ bis _END_ von _TOTAL_ Einträgen',
        'sInfoEmpty': '0 bis 0 von 0 Einträgen',
        'sInfoFiltered': '(gefiltert von _MAX_ Einträgen)',
        'sInfoPostFix': '',
        'sInfoThousands': '.',
        'sLengthMenu': '_MENU_ Einträge anzeigen',
        'sLoadingRecords': 'Wird geladen...',
        'sProcessing': 'Bitte warten...',
        'sSearch': 'Suchen',
        'sZeroRecords': 'Keine Einträge vorhanden.',
        'oPaginate': {
          'sFirst': 'Erste',
          'sPrevious': 'Zurück',
          'sNext': 'Nächste',
          'sLast': 'Letzte'
        },
        'oAria': {
          'sSortAscending': ': aktivieren, um Spalte aufsteigend zu sortieren',
          'sSortDescending': ': aktivieren, um Spalte absteigend zu sortieren'
        }
      },

      rowCallback: function(row, data, index) {
        if (data[29] == 'Abgeschlossen') {
          $(row).css('background-color', '#bfbfbf');
        }
      },

    })
    .on('search.dt', function() {
      var total = table.column(7, {
        page: 'current'
      }).data().sum();
      $('.total-label').text(total);
    });

  var total = table.column(7, {
    page: 'current'
  }).data().sum();
  $('.total-label').text(total);
});
table {
  width: 100%;
  border-collapse: collapse;
}
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>

<h2>
  Total:
  <label class="total-label"></label>
</h2>
<hr>
<table id="liste">
  <thead>
    <tr>
      <td>Column 1</td>
      <td>Column 2</td>
      <td>Column 3</td>
      <td>Column 4</td>
      <td>Column 5</td>
      <td>Column 6</td>
      <td>Column 7</td>
      <td>Column 8</td>
      <td>Column 9</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>abc 1</td>
      <td>abc 1</td>
      <td>abc 1</td>
      <td>abc 1</td>
      <td>abc 1</td>
      <td>abc 1</td>
      <td>abc 1</td>
      <td>1</td>
      <td>hidden</td>
    </tr>
     <tr>
      <td>cdf 2</td>
      <td>cdf 2</td>
      <td>cdf 2</td>
      <td>cdf 2</td>
      <td>cdf 2</td>
      <td>cdf 2</td>
      <td>cdf 2</td>
      <td>2</td>
      <td>hidden</td>
    </tr>
     <tr>
      <td>fgh 3</td>
      <td>fgh 3</td>
      <td>fgh 3</td>
      <td>fgh 3</td>
      <td>fgh 3</td>
      <td>fgh 3</td>
      <td>fgh 3</td>
      <td>3</td>
      <td>hidden</td>
    </tr>
  </tbody>
</table>

您还需要将CssClass="total-label" 添加到您的&lt;asp:Label /&gt; 或您想要的任何类中,以便您可以轻松地在javascript 中引用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多