In an aspx page, there is an asp:linkbutton like this:
<asp:LinkButton runat="server" ID="btExit" Text="Exit"
OnClientClick="javascript:return confirmExit();"
EnableViewState="false"
OnClick="ExitButtonClick"></asp:LinkButton>
And this is the javascript function:
<script type="text/javascript">
function confirmExit() {
bootbox.confirm("Are you sure?", function (confirmed) {
return confirmed;
});
}
</script>
The problem is that, as far as I know, bootbox.confirm works asynchronously, and ExitButtonClick function on code behind is executed without waiting for the user confirmation.
I found a solution that works, using a hidden button:
<asp:LinkButton runat="server" ID="btExit" Text="Exit"></asp:LinkButton>
<asp:Button runat="server" ID="btExitHidden" onclick="ExitButtonClick" style="display:none;" />
And this is the javascript part:
<script type="text/javascript">
$("#btExit").click(function (e) {
e.preventDefault();
bootbox.confirm("Are you sure?", function (confirmed) {
if (confirmed) {
$("#btExitHidden").click();
}
});
});
</script>
My question is if there is a more "beautiful" and "standard" way to work synchronously with a Bootbox.confirm, without using a hidden button.
You can make a custom sync bootbox function this way:
function ayncBootbox(message, cb = null) { // cb : function
return new Promise(resolve => {
bootbox.confirm({
message: message,
buttons: {
confirm: {
label: "Yes"
},
cancel: {
label: "No"
}
},
callback: cb ? result => cb(resolve, result) : result => resolve(result)
})
})
}
then you can call it this way by passing a custom callback if you need to do some extra stuff
var result = await ayncBootbox("message", (resolve, result) => resolve(result))
Or just
var result = await ayncBootbox("message")
PS: don't forget to make the caller function as async as well :) and you can extend this code more with reject if needed
My solution
@Html.ActionLink("Delete", "DeleteReport", new { id = item.Id }, new { @class = "btn btn-danger", onclick = String.Format("return ASE.ConfirmAction(this.href, 'Delete {0}?');", item.Name) })
var ASE = {
ConfirmAction: function (href, text) {
bootbox.confirm(text, function (result) {
if (result)
window.location = href;
});
return false;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.