【问题标题】:Get data from controller action to jquery datatable从控制器操作获取数据到 jquery 数据表
【发布时间】:2019-12-02 08:46:50
【问题描述】:

我正在尝试以 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);
        }

【问题讨论】:

标签: javascript c# jquery asp.net datatables


【解决方案1】:

使用 external jQuery 方法,如 $.ajax()$.post()$.get() 等来填充 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 选项作为回调来操作发送到后端脚本的参数。

【讨论】:

    【解决方案2】:

    控制器:

    [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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 2018-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      相关资源
      最近更新 更多