Inserire un “confirm messagebox” ad un Asp.net Button control

A my colleague asked my a way to create a confirm button in Asp.net. This is the solution:

The Asp.Net button has 2 attributes to trigger a click event OnClick and OnClientClick.

OnClientClick – Calls the client side (JavaScript) event handler
OnClick– Calls the server side (code-behind) event handler

The OnClientClick event handler can be used to perform client side validations and to get a confirmation from the user before triggering the server side event handler as follows.

OnClientClick="if(!confirm('Are you sure you want to Save?')) return false;"
<html>
<head runat="server">
    <title>OnClientClick</title>
</head>
<body>
    <form id="frmOnClientClick" runat="server">
    <div>
        <asp:Button
            id="btnSave"
            runat="server"
            Text="Client Click"
            OnClientClick="if(!confirm('Are you sure you want to Save?'))  
            return false;"
            onclick="btnSave_Click"/>
    </div>
    </form>
</body>
</html>

What do you think?

Annunci