使用SweetAlert2替换ASP.Net按钮上的“ return Confirm()”

Tyl*_*per 4 javascript asp.net sweetalert sweetalert2

在ASP.Net中工作时,我经常喜欢“您确定吗?” 单击诸如删除按钮之类的弹出窗口。这很容易做到:

<asp:Button runat="server" id="btnDelete" Text="Delete" onClientClick="return confirm('Are you sure?');" onClick="btnDelete_Click" />
Run Code Online (Sandbox Code Playgroud)

我真的很喜欢SweetAlert2的确认对话框的样式和一般感觉,但是当我尝试以类似的方式集成它们时,它们似乎有些麻烦。有人可以向我解释如何根据单击的按钮返回SweetAlert2对话框结果以继续还是停止?

到目前为止,这是我得到的:

<asp:Button runat="server" id="btnDelete" Text="Delete" onClientClick="return sweetAlertConfirm();" onClick="btnDelete_Click" />
Run Code Online (Sandbox Code Playgroud)
    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
        });
    }
Run Code Online (Sandbox Code Playgroud)

对话框出现,并且删除不被处理,当然,因为我当前正在执行操作,event.preventDefault()并且没有返回任何内容。我还注意到我可以使用promises.then()在我的后面添加a swal({...}),但是我不确定在这种情况下该如何使用。

如果需要,我可以使用实际上触发代码隐藏方法的隐藏按钮,然后根据用户选择单击该隐藏按钮,以解决问题,但是我希望避免这种情况。

Con*_*Fan 5

由于SweetAlert2对话框是异步处理的,因此必须在解决承诺后以编程方式触发另一个按钮单击。除了创建隐藏按钮外,您还可以btnDelete通过设置标志来指示操作已被确认来重用。处理第二次单击时将检测到该标志,并且将允许继续单击按钮并触发服务器事件。

<asp:Button ... OnClientClick="return sweetAlertConfirm(this);" OnClick="btnDelete_Click" />
Run Code Online (Sandbox Code Playgroud)
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
        });
    }
}
Run Code Online (Sandbox Code Playgroud)