[英]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.