I'm working on an ASP.NET MVC application and currently iterating a list of records as rows of a table to implement jQuery DataTables plugin to it. I have the following structure:
//Contact Card Layout:
<table id="contactTable" style="width:100%;">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>
<!-- Contact Card -->
<div class="contactCard" isprimary="@Model[i].IsPrimary.SelectedValue">
//Contact Card UI Logic
</div>
</td>
</tr>
}
</tbody>
</table>
The Jquery script for rendering it as a datatable is:
<script>
$(document).ready(function () {
var table = $('#contactTable').DataTable({
"filter": false, //show-hide search box
"paginate": true, //show-hide pagination control
"pagingType": "simple_numbers", //Pagination type; currently there are multiple styles [numbers, simple, simple_numbers, ]
"pageLength": 3, //The page size to specify the length for pagination
"lengthChange": false, // show hide dropdown
//"lengthMenu": [[2, 5, 10, 15, -1], [2, 5, 10, 15, "All"]],
"info": true, //hide showing entries
"drawCallback": function () {
//var row = this.api().row('#contactTable tbody tr td .contactCard[isprimary = "Y"]').index();
//alert(row);
}
});
});
</script>
It is all working fine as the required UI but there is one issue with re-rendering the table in case of a new row is added to the table. I have a Bootstrap Modal popup which calls the controller method and adds a new record to the Model and hence returns the list of all records (updated/added ones also) which shows on the UI as the table but gets append at the end of the table.
How can I sort the rows in datatable for the last one added to be displayed on top? Note: I'm sending the sorted list of records from the controller but it is not shown in the same order in UI. Some links mentioned to use "drawCallback" method of Datatables to drop and recreate the table but it is not working for me. Any inputs will be really helpful.