JQuery 数据表将列 类 添加到动态内容

JQuery datatables adding column classes to dynamic content

我有一个包含动态列的数据table

<table id="dt_basic" width="100%" class="table table-striped table-bordered table-hover tableSearch">
    <thead>
        <tr>
            @foreach (var item in Model.ColumnInfo) {
            <th>@Html.Raw(@item.ColumnHeader) </th>
            }
            <th>Edit</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

我想在填充数据table后设置列类型和列class

    var table = $('#dt_basic').dataTable({
        "pagingType": "full_numbers",
        "ajax": "@Url.Action("LoadResultGrid", "Verifications", new { id = Model.RunId })",
        "deferRender": true,
        "bProcessing": true,
        "scrollX": "100%",
        "columnDefs": [
            {
                "targets": [0],
                "visible": false,
                "searchable": false
            },
            {
                "targets": [1],
                "searchable": true,
                "visible": true
            }
        ]
    });

Model.ColumnInfo 是 objects 的列表,其属性为:ColumnHeader、ColumnType、ColumnClass。

所以我需要在创建 table 之后遍历列并将列 header 匹配到 Model.ColumnInfo.ColumnHeader 然后将列类型设置为相应的 Model.ColumnInfo.ColumnType 和列 class 对应 Model.ColumnInfo.CoulmnClass.

如有任何帮助,我们将不胜感激。谢谢

我已经找到解决问题的方法,我想我会分享它以防其他人遇到类似问题。

我添加了 razor 代码来生成 javascript,它动态地将 clasName 属性添加到 columndefs。

    var table = $('#dt_basic').dataTable({
        "pagingType": "full_numbers",
        "ajax": "@Url.Action("LoadResultGrid", "Verifications", new { id = Model.RunId })",
        "deferRender": true,
        "bProcessing": true,
        "scrollX": "100%",
        "columnDefs": [
            {
                "targets": [0],
                "visible": false,
                "searchable": false
            },
            @for(var i = 0; i < (Model.ColumnHeaders.Count); i++){
                if (Model.ColumnHeaders[i].ColumnClass != null)
                {
                    @: {"targets": [@i], "className": "@Model.ColumnHeaders[i].ColumnClass"},
                };
            }
        ]
    });

已解决的 javascript 片段:

        "columnDefs": [
            {
                "targets": [0],
                "visible": false,
                "searchable": false
            },
                     {"targets": [5], "className": "do_rightalign"},
                     {"targets": [6], "className": "do_rightalign"},
                     {"targets": [7], "className": "do_rightalign"},
                     {"targets": [8], "className": "do_rightalign"},