我尝试显示自定义提醒框以确保用户想要删除项目。删除该项目后,将打开一个新的警告框并说“"该项目已删除"”,然后用户必须单击“确定”按钮。
我的问题是,在删除项目后,页面将重定向到其他页面而不单击“确定”按钮。我如何安排代码来实现我的观点。
控制器;
public ActionResult Delete(int id)
{
Category category = db.Categories.Find(id);
db.Categories.Remove(category);
db.SaveChanges();
return RedirectToAction("Index");
}
删除按钮;
<button type="button" class="btn bg-red waves-effect" onclick="Delete();">Delete</button>
警报脚本;
<script>
function Delete()
{
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
},
function () {
location.href = '@Url.Action("Delete", "Categories", new { id = Model.Id })',
swal({
title: "Deleted!",
text: "Your imaginary file has been deleted.",
type: "success"
})
});
}
</script>
答案 0 :(得分:1)
当您执行第location.href="Categories/Delete/123"
行时,浏览器基本上会将当前页面重定向到这个新网址,实际上是在发出新的GET请求。如果您只想从服务器中删除该项目并向用户显示警告,您希望通过ajax进行该操作。
因此,在“确认删除”按钮中单击的回调,对服务器进行ajax调用。您可以使用jQuery $.post
方法。
function Delete() {
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
},
function() {
var url = '@Url.Action("Delete", "Home", new {id = Model.Id})';
$.post(url,
function(response) {
if (response.success === "success") {
swal({
title: "Deleted!",
text: "Your imaginary file has been deleted.",
type: "success"
});
} else {
// failed to delete. show messaage to user
alert(response.message);
}
});
});
}
此外,由于您通过ajax进行Delete方法调用,因此您可以返回json响应而不是重定向响应。我还建议在删除操作时保持HttpPost操作,因为它会更改数据。
[HttpPost]
public ActionResult Delete(int id)
{
try
{
Category category = db.Categories.Find(id);
db.Categories.Remove(category);
db.SaveChanges();
if(Request.IsAjaxRequest())
{
return Json(new { status = "success" });
}
return RedirectToAction("Index");
}
catch(Exception e)
{
return Json(new { status = "failed",message=e.Message });
}
}