SweetAlert 使用@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 操作总是 运行。

首先,您当前的代码正在导航到删除操作。任何正在更改数据的操作方法都不应该是 Http GET 操作方法。它应该在 Http Post 操作方法中。

[HttpPost]
public ActionResult Delete(string roleName)
{
    // to do  : Delete and return something
}

现在因为我们的 Delete 方法是 HttpPost,你需要一个表单提交,而不是通过浏览器导航到 link(这是一个 GET 请求) .因此,在删除按钮周围构建一个表单标签(将角色名称保留在表单的隐藏字段中),监听此按钮上的 click 事件,防止导航到新 url 的正常行为,而是显示甜蜜警报,并在 then 回调(用户确认 "Yes")中提交表单。

@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();
        });

    });

})