Confirm postback OnClientClick button ASP.NET

makambi picture makambi · Dec 27, 2012 · Viewed 183.1k times · Source
<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
                           OnClick="BtnUserDelete_Click"
                           OnClientClick="return UserDeleteConfirmation();" 
 meta:resourcekey="BtnUserDeleteResource1" />

I have tried:

function UserDeleteConfirmation() {
        if (confirm("Are you sure you want to delete this user?"))
            return true;
        else
            return false;
}

and

function UserDeleteConfirmation() {
    if (confirm("Are you sure you want to delete this user?")) {
            __doPostBack(btnUserDelete, '');
    }

    return false;
 }

And none of them works.

Answer

Hans Kesting picture Hans Kesting · Dec 27, 2012

Try this:

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
                       OnClick="BtnUserDelete_Click"
                       OnClientClick="if ( ! UserDeleteConfirmation()) return false;" 
 meta:resourcekey="BtnUserDeleteResource1" />

This way the "return" is only executed when the user clicks "cancel" and not when he clicks "ok".

By the way, you can shorten the UserDeleteConfirmation function to:

function UserDeleteConfirmation() {
    return confirm("Are you sure you want to delete this user?");
}