I’m trying to use the DataTables jQuery plug-in in MVC3 using an ajax request as the data source for the table.
I have a View called “Search” which contains a search form…under the form, I have the following html…
<table id="caseTable" class="clear full-width dataTable">
<thead>
<tr>
<th>Case Name</th>
<th>Court</th>
<th>Case Number</th>
<th>Case Filed Date</th>
<th>Chapter</th>
<th>Last Researched</th>
<th>Disposition</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
When the search form is submitted, an ajax call is sent off the get the tr elements for each record to be displayed in the table.
$.ajax({
url: "/Home/SearchForCases",
type: "POST",
data: {
CaseNumber: caseNumber,
DebtorLastName: lastName,
Last4SSN: last4SSN,
FullSSN: fullSSN,
StartDate: $("#StartDate").val(),
EndDate: $("#EndDate").val(),
SelectedCourtDistrictId: $("#SelectedCourtDistrictId").val(),
SelectedChapterId: $("#SelectedChapterId").val()
},
success: function (result) {
$("#caseTable > tbody").html(result);
$("#caseTable").dataTable({
"bDestroy": true,
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"asStripClasses": ["white-highlight"],
"bAutoWidth": false
});
$("#caseTable > tbody > tr").dblclick(function () {
$(this).removeClass("white-highlight").addClass("yellow-highlight");
});
},
complete: function () {
$("#ajaxProgress").dialog('close');
$("#searchResults").show();
}
});
Everything loads up fine on the first call, but on subsequent calls, the data returned from the ajax call is being appended vs replaced. I have checked the html being returned from the ajax call and it’s always returning one row of data, <tr><td></td></tr> only.
Add the bDestroy option to remove the old datatable formatting first. You could also try removing the bRetrieve option.
Edit
If possible, it might be better to change your code so you can use the built in datatable ajax functionality by passing in the sAjaxSource option when creating the datatable. This would require you to change your server side code to return json of data instead of html.
If that isn’t possible, then you should use fnClearTable to clear the existing data before adding the new data.