简体   繁体   English

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

[英]Get data from controller action to jquery datatable

I'm trying to get some data from controller action in JSON format then send it to DataTables using AJAX, the data is shown but when I search or sort the data disappears and "no data found" message displayed, also there's no longer any pages it's just one long table. 我正在尝试从控制器操作中以JSON格式获取一些数据,然后使用AJAX将其发送到DataTables,显示了数据,但是当我搜索或排序数据时就消失了,并且显示了“未找到数据”消息,也不再有任何页面这只是一张长桌子。

HTML 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>

Script: 脚本:

$(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's action: 管制员的行动:

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

Using external jQuery methods, like $.ajax() , $.post() , $.get() and such to populate DataTable is extremely bad practice as you end up coping with the mess of workarounds to make your data get loaded into table where and when it is necessary. 使用$.ajax()$.post()$.get()类的外部 jQuery方法填充DataTable是非常糟糕的做法,因为您最终要解决各种变通方法,以使您的数据加载到表中何时何地是必要的。 Instead, I suggest to employ ajax option. 相反,我建议使用ajax选项。

Another bad choice is cooking up table body HTML manually. 另一个不好的选择是手动编写表主体HTML。 DataTables can perfectly do that for you, should you just point to column data source with columns / columnDefs options. 如果您仅使用columns / columnDefs选项指向列数据源,则DataTables可以为您完美地做到这一点。

In order to get some table column rendered as an arbitrary HTML there is another option columns.render . 为了使某些表列呈现为任意HTML,还有另一个选项columns.render

And, finally, you may append HTML attributes to your cell using columns.createdCell option. 最后,您可以使用columns.createdCell选项将HTML属性附加到单元格中。

So, your complete jQuery code might look something, like: 因此,您完整的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');
        }
    });
});

While your HTML may be as simple, as: HTML可能很简单,例如:

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

And your CSS I'd recommend to put into separate file. 我建议将您的CSS放在单独的文件中。

In order to reload your data when necessary you may simply invoke ajax.reload() method, benefiting from ajax.data option as a callback to manipulate parameters sent to the backend script, if needed. 为了在必要时重新加载数据,您可以简单地调用ajax.reload()方法,并ajax.data选项作为回调来处理发送给后端脚本的参数(如果需要)。

controller: 控制器:

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


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



                        }).ToArray()
            };

     return JsonData;
}

for script: 对于脚本:

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