I want to select multiple rows and then click on a button to approve/deny those rows. I have successfully updated the rows I want to approve in db. But when ajax callback, I ran table.draw() and it doesn't show the saved result. I don't know how to take the saved result and refresh back to the DataTable.
Also I am new to MVC and jQuery, I was fumbling around to make it barely work. Could you help point out what do I need to improve/fix to make this work better?
Here are my codes:
View (table part):
<table id="myDataTable" class="display">
<thead>
<tr>
<th>Clearance Name</th>
<th>Approved</th>
<th>Approver</th>
<th>DateTime</th>
<th>Deny Reason</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Request.RequestClearances)
{
<tr id="@item.RequestClearanceID">
<td>@item.Clearance.ClearanceName</td>
<td>@item.IsApproved</td>
<td>@item.ApprovedUser</td>
<td>@item.ModifiedDate</td>
<td>@item.DenialReason</td>
</tr>
}
</tbody>
</table>
<div><input type="button" id="btnApprove" value="Approve" /><input type="button" id="btnDeny" value="Deny" /></div>
View (jQuery part):
<script>
$(function () {
var table = $("#myDataTable").DataTable();
$("#myDataTable tbody").on('click', 'tr', function () {
var tr = $(this).closest("tr");
var rowText = tr.children("td").text();
if (! rowText.match("True") ) {
$(this).toggleClass('selected');
}
});
$("#btnApprove").click(function () {
var idArray = $.map(table.rows('.selected').ids(), function (item) {
return item;
});
$.ajax({
type: "POST",
url: '@Url.Action("UpdateApproveDeny")',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ requestClearanceIDs: idArray, isApproved: "true" }),
success: function () {
table.draw();
},
error: function (jqXHR, textStatus, errorThrown) {
$("#message").text(JSON.stringify(jqXHR).toString());
alert("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
});
});
</script>
Control:
public JsonResult UpdateApproveDeny(string[] requestClearanceIDs, string isApproved)
{
if (requestClearanceIDs == null) return Json("fail",JsonRequestBehavior.AllowGet);
int? requestID = 0;
foreach (var requestClearanceID in requestClearanceIDs)
{
int id = 0;
Int32.TryParse(requestClearanceID, out id);
requestID = rc.RequestID;
rc.IsApproved = Convert.ToBoolean(isApproved);
rc.ModifiedBy = User.Identity.Name;
rc.ModifiedDate = DateTime.Now;
rc.ApprovedUser = User.Identity.Name;
db.SaveChanges();
}
return Json("success",JsonRequestBehavior.AllowGet);
}