在ASP.Net工作时,我经常喜欢“你确定吗?”单击删除按钮之类的弹出窗口。这很容易做到:
<asp:Button runat="server" id="btnDelete" Text="Delete" onClientClick="return confirm('Are you sure?');" onClick="btnDelete_Click" />
我非常喜欢SweetAlert2确认对话的造型和一般感觉,但是当我试图以类似的方式整合它们时,它们似乎有点麻烦。有人可以向我解释如何根据点击的按钮将SweetAlert2对话框结果返回到是继续还是停止?
这是我到目前为止所得到的:
<asp:Button runat="server" id="btnDelete" Text="Delete" onClientClick="return sweetAlertConfirm();" onClick="btnDelete_Click" />
function sweetAlertConfirm() {
event.preventDefault();
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() {
// CONFIRM WAS CHOSEN
// }, {function() {
// CANCEL WAS CHOSEN
});
}
当然,对话框出现并且没有处理删除,因为我正在进行event.preventDefault()
并且没有返回任何内容。我也注意到I can use promises,在.then()
之后添加了swal({...})
,但是我不确定在这种情况下如何使用它。
如果需要,我可以通过实际触发代码隐藏方法的隐藏按钮变得棘手,并根据用户选择单击该隐藏按钮,但我希望避免这种情况。
答案 0 :(得分:4)
由于SweetAlert2对话框是异步处理的,因此在解析promise时,必须以编程方式触发另一个按钮。您可以通过设置标志来重复btnDelete
,而不是创建隐藏按钮,以指示操作已经确认。处理第二次单击时将检测到该标志,并且将允许按钮单击继续并触发服务器事件。
<asp:Button ... OnClientClick="return sweetAlertConfirm(this);" OnClick="btnDelete_Click" />
function sweetAlertConfirm(btnDelete) {
if (btnDelete.dataset.confirmed) {
// The action was already confirmed by the user, proceed with server event
btnDelete.dataset.confirmed = false;
return true;
} else {
// Ask the user to confirm/cancel the action
event.preventDefault();
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 () {
// Set data-confirmed attribute to indicate that the action was confirmed
btnDelete.dataset.confirmed = true;
// Trigger button click programmatically
btnDelete.click();
}).catch(function (reason) {
// The action was canceled by the user
});
}
}
答案 1 :(得分:0)
var obj = { status: false, ele: null };
function DeleteConfirm(btnDelete) {
if (obj.status) {
obj.status = false;
return true;
};
Swal.fire({
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((result) => {
if (result.value) {
obj.status = true;
//do postback on success
obj.ele.click();
Swal.fire({
title: 'Deleted!',
text: 'Your file has been deleted.',
type: 'success',
timer: 800
})
}
});
obj.ele = btnDelete;
return false;
}
<link href="https://cdn.jsdelivr.net/npm/sweetalert2@8/dist/sweetalert2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@8/dist/sweetalert2.min.js"></script>
<asp:LinkButton ID="cmdDelete" runat="server" CausesValidation="False" OnClientClick="return DeleteConfirm(this);">