SweetAlert确认提示使用 @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,但问题是,无论我是否取消,操作链接操作始终是运行的。

首先,您当前的代码正在导航到删除操作。任何正在更改数据的操作方法都不应为HTTP获取动作方法。它应该在HTTP后的操作方法中。

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

最新更新