我正在使用 SweetAlert2替换我的 MVC5 应用程序中的 javascript 警报。我的问题是:如何在运行删除操作之前使用 sweetalert 确认。例如,这很好用....
<span onclick="return confirm('Are you sure to delete?')">
@Html.ActionLink("Delete", "Delete", new { roleName = @role.Name }, new { @class = "btn btn-success btn-xs" })
</span>
如果我取消删除操作则不会运行。如果我单击确定,它会正常运行。
但我想使用 SweetAlert2。基本上这里是提示....
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function () {
swal(
'Deleted!',
'Deleted.',
'success'
)
})
问题是我不确定如何用这段代码替换确认并让它正常工作。
我尝试将上述代码包装在一个函数中,如果成功则返回 true,但问题是无论我是否取消,ActionLink 操作始终运行。
最佳答案
首先,您当前的代码正在导航到删除操作。任何正在更改数据的操作方法都不应该是 Http GET 操作方法。它应该在 Http Post 操作方法中。
[HttpPost]
public ActionResult Delete(string roleName)
{
// to do : Delete and return something
}
现在因为我们的 Delete
方法是 HttpPost,你需要一个表单提交,而不是通过浏览器导航到一个链接(这是一个 GET
请求)。所以在你的删除按钮周围构建一个表单标签(将 roleName 保留在表单的隐藏字段中),监听此按钮上的 click
事件,防止导航到新 url 的正常行为,相反,显示甜蜜警报,并在 then
回调(用户确认"is")中提交表单。
@using (Html.BeginForm("Delete", "Home"))
{
<input type="hidden" name="roleName" value="admin" />
<span>
@Html.ActionLink("Delete", "Delete", null,
new { @class = "btn btn-success btn-xs deleteBtn" })
</span>
}
和javascript
$(function () {
$(".deleteBtn").click(function (e) {
//whenever our button is clicked
e.preventDefault();
// stop the default behavior(navigation)
var _form = $(this).closest("form");
//get a reference to the container form
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function () {
//user selected "Yes", Let's submit the form
_form.submit();
});
});
})
关于javascript - SweetAlert 使用@Html.ActionLink 确认提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42354460/