javascript - 从 Controller 操作获取数据到 jquery 数据表

标签 javascript c# jquery asp.net datatables

我试图从 JSON 格式的 Controller 操作中获取一些数据,然后使用 AJAX 将其发送到 DataTables,数据会显示,但是当我搜索或排序时,数据会消失,并且显示“未找到数据”消息,也没有任何页面都更长,它只是一张长 table 。

HTML 表格:

<table id="demoGrid" class="table  table table-hover dt-responsive nowrap" width="100%" cellspacing="0">
    <thead>
        <tr class="styleHeaderTab">
            <th class="th-sm">
                Matricule
            </th>
            <th class="th-sm">
                Intitulé
            </th>
            <th class="th-sm">
                Nombre de compte
            </th>
            <th class="">
            </th>
        </tr>
    </thead>
    <tbody id="chargeHolder"></tbody>
</table>

脚本:

$(document).ready(() => getActif());
$('#demoGrid').dataTable({
        "language": {
            "search": "Rechercher",
            "lengthMenu": "Afficher _MENU_ chargés par page",
            "info": "Page: _PAGE_ / _PAGES_",
            "paginate": {
                "next": "Suivante",
                "previous": "Précédente"
            }
        }
    });
function getActif() {
        $.ajax({
            url: '/ChargeAffaire/GetActif',
            method: 'get',
            dataType: 'json',
            error: (err) => console.log(err),
            success: (res) => {
                let s="";
                for (let i=0;i<res.length;i++) {
                    s +=`<tr>
                            <td>${res[i].matricule}</td>
                            <td>${res[i].intitule}</td>
                            <td> 59</td>
                            <td id="linkContainer">
                                <a class="cls no-href" id="detail" onclick="update_url('consulter/${res[i].id}')" data-toggle="modal" data-target="#exampleModal">consulter</a>
                                <br/>
                                <a class="no-href" id="conge" onclick="updateConge(${res[i].id})" data-toggle="modal" data-target="#dateMission">Ajouter un congé</a>
                                <br/>
                                <a class="no-href" id="ajout"  onclick="updateAction(${res[i].id})" data-toggle="modal" data-target="#ajoutModal">Ajouter un compte</a>
                            </td>
                        </tr>`;
                }
                $("#chargeHolder").html(s);
                $(".no-href").css({"cursor":"pointer","color":"#077bb1"});
                $(".no-href").parent().css("text-align","center");
            }
        });
    }

Controller 的操作:

[HttpGet]
        public ActionResult GetActif()
        {
            var list = ListCharges.list.FindAll(x => x.conge.etat == "Actif");
            return Json(list);
        }

最佳答案

使用外部 jQuery 方法,例如 $.ajax()$.post()$.get() 等填充 DataTable 是极其不好的做法,因为您最终会处理困惑的解决方法,以使数据在必要的位置和时间加载到表中。相反,我建议使用 ajax选项。

另一个糟糕的选择是手动编写表体 HTML。如果您只需使用 columns 指向列数据源,DataTables 就可以完美地为您做到这一点。/columnDefs选项。

为了将某些表列呈现为任意 HTML,还有另一个选项 columns.render .

最后,您可以使用 columns.createdCell 将 HTML 属性附加到单元格中选项。

所以,完整的 jQuery 代码可能看起来像这样:

$(document).ready(() => {
    $('#demoGrid').dataTable({
        ajax: {
            url: '/ChargeAffaire/GetActif'
        },
        language: {
            search: "Rechercher",
            lengthMenu: "Afficher _MENU_ chargés par page",
            info: "Page: _PAGE_ / _PAGES_",
            paginate: {
                next: "Suivante",
                previous: "Précédente"
            }
        },
        columns: [
            {title: 'Matricule', data: 'matricule'},
            {title: 'Intitulé', data: 'intitule'},
            {title: 'Nombre de compte', data: () => ' 59'},
            {
                title: '', 
                data: rowData => `
                    <a class="cls no-href" id="detail" onclick="update_url('consulter/rowData.id')" data-toggle="modal" data-target="#exampleModal">consulter</a>
                    <br/>
                    <a class="no-href" id="conge" onclick="updateConge(rowData.id)" data-toggle="modal" data-target="#dateMission">Ajouter un congé</a>
                    <br/>
                    <a class="no-href" id="ajout"  onclick="updateAction(rowData.id)" data-toggle="modal" data-target="#ajoutModal">Ajouter un compte</a>`,
                createdCell: td => $(td).attr('id', 'linkContainer')
            }
        ],
        //append custom classes for the first 3 <th> and id attribute to <tbody>
        renderCallback: function(){
            this.api().columns().every(function(){
                if(this.index() < 3) $(this.header()).addClass('th-sm');
            });
            $('#demoGrid tbody').attr('id', 'chargeHolder');
        }
    });
});

虽然您的 HTML 可能很简单,例如:

<table id="demoGrid" class="table  table table-hover dt-responsive nowrap" width="100%" cellspacing="0"></table>

我建议您将 CSS 放入单独的文件中。

为了在必要时重新加载数据,您只需调用 ajax.reload()方法,受益于ajax.data如果需要,选项作为回调来操作发送到后端脚本的参数。

关于javascript - 从 Controller 操作获取数据到 jquery 数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57178824/

相关文章:

javascript - Express.js 应用程序错误导致 Route.post() 需要回调函数但出现 [object Undefined] 错误

javascript - 循环访问 AWS Lambda Nodejs SDK 函数

c# - 连接数据源之间的选择 C#

javascript - 弹出窗口内的 JQuery UI Datepicker

java - 如何从 JSON 转换为 JSONP?

javascript - 从 Summernote 中的光标位置获取上一个单词

javascript - 部分 API 在 NodeJS 中不起作用。我如何解决它?

javascript - 如何在html中使用url参数?

c# - 如何避免参数化 SQL 查询中的无效 UTF8 字节序列?

c# - Azure 搜索 v11 : Indexing nullable Collection of Complex Type