AJAX 删除函数不会在控制器中调用相关操作



我正在实现asp.net核心3.1项目。在我的项目中,我有一个"索引"视图,它显示了一个记录表,每个记录附近都有一个删除按钮。用户点击"删除"按钮后,我调用jQueryAjaxDelete函数(位于site.js中(,并向其发送Delete操作及其控制器容器。现在我的问题是,当我点击"删除"按钮时,会显示一条确认消息,但在点击该按钮删除记录后,它不会在Gate控制器中调用"删除"操作,因此不会删除记录。以下是我尝试过的:索引视图:

<div id="tablecontainer" class="my-5 col-sm-12 p-4">
<table id="myDummyTable" class="table">
<thead>
<tr id="headerrow">

<th>
Desc
</th>
<th>
Operation
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>

<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>


<a onclick="jQueryAjaxDelete('@Url.Action("Delete","Gates",new {id=item.Id},Context.Request.Scheme)','Delete')" class="btn btn-info text-white"><i class="fas fa-pencil-alt"></i> delete</a>

</td>
</tr>
}
</tbody>
</table>
</div>

以下是闸门控制器中的删除操作:

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id)
{
Console.WriteLine("Deleted id:" + id);
var gate = await _context.Gate.FindAsync(id);
gate.IsDeleted = true;
_context.Gate.Update(gate);
await _context.SaveChangesAsync();
//return RedirectToAction(nameof(Index));
return Json(new { html = Helper.RenderRazorViewToString(this, "_ViewAll", _context.Gate.ToList()) });
}

这是站点.js:中的jQueryAjaxDelete

jQueryAjaxDelete = form => {

if (confirm('Are you sure to delete this record?')) {

try {
$.ajax({
type: 'POST',
url: form.action,
data: new FormData(form),
contentType: false,
processData: false,
success: function (res) {
$('#view-all').html(res.html);
},
error: function (err) {
console.log('confirm deleteAjax error');
console.log(err);
}
})
} catch (ex) {
console.log(ex)
}
}

如果有人向我提出解决方案,我将不胜感激。

  1. 您需要在前端添加RequestVerificationToken,因为您在后端添加了[ValidateAntiForgeryToken]
  2. 表单本身就是一个url。你可以直接使用它
  3. 您已将参数与querystring一起传递。因此,您可以删除FormData

下面是可以调用操作的代码。

<!--in .cshtml-->
@Html.AntiForgeryToken()

@section Scripts{
<script>
var jQueryAjaxDelete = form => {

if (confirm('Are you sure to delete this record?')) {
console.log(form)
try {
$.ajax({
type: 'POST',
url: form,
headers: {
RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (res) {
$('#view-all').html(res.html);
},
error: function (err) {
console.log('confirm deleteAjax error');
console.log(err);
}
})
} catch (ex) {
console.log(ex)
}
}
}
</script>
}

如果<a>在单击时重新加载或重定向,则可以将事件传递到jQueryAjaxDelete并使用此方法。

event.preventDefault()

最新更新