I am having an issue with Datatables and deletion in my MVC application. I have a button for each row that when clicked opens up a modal window that asks the user if they want to delete that row. If they click "OK", the data is removed from my database, the row deleted is deleted, and the window closes. This all works as expected when I delete one row. However, problems arise when I attempt to delete any other row after my first delete (without refreshing the page).
When I click on the delete for a second time, my function first attempts to delete the initial row again and fails because it does not exist anymore. Then it immediately and successfully deletes the new row I asked to delete. I have have console outputs that tell me what ID the delete function has and they revealed that the old ID is being re-passed to the function first.
Here is my ouput if I delete one row (with ID = 87) and then delete another (with ID = 84) without refreshing the console or page
clicked delete on 87
Deleting #87
DELETE http://localhost:49773/api/IncidentAPI/87
200 OK
Deleted
clicked delete on 87
Deleting #87
DELETE http://localhost:49773/api/IncidentAPI/87
500 Internal Server Error
clicked delete on 84
Deleting #84
DELETE http://localhost:49773/api/IncidentAPI/84
200 OK
"NetworkError: 500 Internal Server Error - http://localhost:49773/api/IncidentAPI/87"
Deleted
Here is the code for my delete button in each row
$('.Delete').unbind().on("click", function () {
var tr = $(this).closest('tr');
var ID = dataLog.row(tr).data()[16];
tr.addClass('deleteHighlight');
$('#deleteWindow').dialog('open');
$('.deleteOK').on("click", function () {
console.log("clicked delete on " + ID);
deleteIncident(ID); // deletes the row with that ID
$('.Details').bind();
});
$('.deleteClose').on('click', function (event, ui) {
console.log("Close delete");
tr.removeClass('deleteHighlight', 500);
$('#deleteWindow').dialog('close');
});
});
Here is my delete method
function deleteIncident(ID) {
var rowID = '#' + ID;
console.log("Deleting " + rowID);
$.ajax({
url: '/api/IncidentAPI/' + ID,
type: 'DELETE',
contentType: "application/json; charset=utf-8",
success: function (results) {
console.log("Deleted");
dataLog.row(rowID).remove().draw();
$('#deleteWindow').dialog('close');
}
});
}