简体   繁体   中英

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.

HTML table:

<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. Instead, I suggest to employ ajax option.

Another bad choice is cooking up table body HTML manually. DataTables can perfectly do that for you, should you just point to column data source with columns / columnDefs options.

In order to get some table column rendered as an arbitrary HTML there is another option columns.render .

And, finally, you may append HTML attributes to your cell using columns.createdCell option.

So, your complete jQuery code might look something, like:

$(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:

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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