The following code sample illustrates a client side (javascript) confirm box in use with an aspx button, this presents the end user with a dialog box asking ”are you sure you want to submit this form?’, it gives the user two options ‘Ok’ and ‘Cancel’, clicking ok will submit the form, clicking cancel will not
This sample code uses 4 variations;
- TestButton1 - a standard html input type ‘button’, which submits the page using hand coded js
- TestButton2 - a standard html input type ‘submit’, it has the default behaviour of submitting the form
- TestButton3 - an asp:button with the OnClientClick (rendered as onclick) declared in the mark up
- TestButton4 - an asp:button with the onclick defined in the code behind or c#
The aspx page markup - JavaScriptConfirm.aspx
The c# ‘code-behind’
The ‘key’ here is the return in the onclick method; the javascript confirm will return true if ‘Ok’ is clicked and false if ‘Cancel’ is clicked, we must return this value from our buttons onclick event so that the form will not generate an HTTP POST (or PostBack if you like)
if you do not include the return statement in the onclick the form will post back regardless of which button is clicked ‘Ok’ or ‘Cancel’; for instance you do NOT want to do this
onclick="AreYouSure();"
but instead do this
onclick="return AreYouSure();"