【发布时间】:2015-12-22 15:43:16
【问题描述】:
我想选择多行,然后单击一个按钮来批准/拒绝这些行。我已经成功更新了我想在 db 中批准的行。但是当 ajax 回调时,我运行了 table.draw() 并且它没有显示保存的结果。我不知道如何获取保存的结果并刷新回 DataTable。
我也是 MVC 和 jQuery 的新手,我一直在摸索以使其几乎无法工作。您能否帮助指出我需要改进/修复什么才能使这项工作更好?
这是我的代码:
视图(表格部分):
<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>
视图(jQuery 部分):
<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>
控制:
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);
}
【问题讨论】:
-
由于您以静态方式使用 DataTables,因此您需要 replace your table content in the AJAX callback 然后重新绑定
$("#myDataTable").DataTable(),因为原始表已被替换。我以前没有使用过 DataTables,但它似乎有 built-in AJAX support - 这将要求您提供一个 AJAX 操作,以 JSON 格式返回您的表数据。
标签: jquery ajax asp.net-mvc-5 datatables