简体   繁体   中英

datatables asp.net core razor pages IActionResult new JsonResult

How I can set the table content on selection change I am talking about datatables.js library, via jquery ajax post. How I can return new JsonResult and redraw the table's content with the result from the handler ? Thanks

Here is the process I use: Summary:

  1. Declare a js variable at a top level scope

  2. In the document.ready function, instantiate the data table to your global js variable

  3. On ajax post clear the table via the stored object and then iterate the results and add the rows

More in depth:

//declare this high in scope so you can access it in your functions
var dt;

$(document).ready(function () {
   //Create the datatable and assign it to variable for later reference
   dt = $('#MyTable').DataTable({dom: 'Bfrtip'});
});

$("#SomeBtn").click(function () {
  //clear current table rows
  dt.clear().draw();
  $.ajax({
         url: whatever Path,
         data: whatever Data,
            dataType: "json",
            type: "POST",
            cache: false,
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                $.each(data, function (i, n) {
                    //Iterate results and add each to the table. This is why we stored the datatable in a highr scope so we can operate it on it here :)
                    dt.row.add([n.prop1, n.prop2, n.prop3]).node().id = n.propID + '_Row';
                    dt.draw(false);

                });
            },
            error: function (response) {
            },
            failure: function (response) {

            }
        });
 });

As you can see, by storing the datatable in an object when you instatiate it, you can control it in later functions per its api

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