繁体   English   中英

从控制器动作获取数据到jquery数据表

[英]Get data from controller action to jquery datatable

我正在尝试从控制器操作中以JSON格式获取一些数据,然后使用AJAX将其发送到DataTables,显示了数据,但是当我搜索或排序数据时就消失了,并且显示了“未找到数据”消息,也不再有任何页面这只是一张长桌子。

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");
            }
        });
    }

管制员的行动:

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

使用$.ajax()$.post()$.get()类的外部 jQuery方法填充DataTable是非常糟糕的做法,因为您最终要解决各种变通方法,以使您的数据加载到表中何时何地是必要的。 相反,我建议使用ajax选项。

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

为了使某些表列呈现为任意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选项作为回调来处理发送给后端脚本的参数(如果需要)。

控制器:

[HttpGet] public ActionResult GetActif(){
                total = list.Count,
                rows = (from u in list
                        select new
                        {


                            id = u.Id,
                            Name = u.sName,



                        }).ToArray()
            };

     return JsonData;
}

对于脚本:

dataType: 'json',
success: function (result) {
    $("#action").text("");
    var html = '';$.each(result.rows, function (key, item) {
        html += '<tr>';
        html += '<td class="text-center">' + item.id + '</td>';
        html += '<td class="text-center">' + item.Name + '</td>';});
    $('#demoGrid tbody').html(html);
    $('#demoGrid').DataTable({}, error: function (error) {
    return error;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM