[英]Is it possible to add both a css class AND a return confirm on an Html.ActionLink?
[英]SweetAlert Confirm prompt with @Html.ActionLink
我正在使用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动作。
首先,您当前的代码导航到delete操作。 任何更改数据的操作方法都不应该是Http GET操作方法。 它应该在Http Post操作方法内。
[HttpPost]
public ActionResult Delete(string roleName)
{
// to do : Delete and return something
}
现在,由于我们的Delete
方法是HttpPost,因此您需要提交表单,而不是通过浏览器导航到链接(这是GET
请求)。 因此,围绕您的删除按钮构建一个表单标签(将roleName保留在表单的隐藏字段中),侦听此按钮上的click
事件,防止导航到新url的正常行为,而是显示甜蜜的提醒,然后在then
回调中(用户确认为“是”),提交表单。
@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();
});
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.