Adding a pop-up confirmation box to cancel form submission without postback

Question

How do I add a pop-up confirmation dialog box that will allow a user, after having clicked Submit, to cancel form submission, without the form doing a postback?

Background

By default, a .NET button control will initiate a postback when it is clicked. To prevent this, you must add the "return false;" statement to the JavaScript OnClick event of the button.

Solutions

There are two simple ways to do this.

Method 1

If you only have a confirmation dialog without too much script to show, you can add inline code directly to either the OnClick attribute or OnClientClick property of the submitButton depending on whether or not you’re using the Form Designer. The following are examples of inline code for each.

If you’re using the Form Designer, add the following code to the .NET code of your web form:

protected void Page_Load(object sender, EventArgs e)
{
  base.Page_Load(sender, e);  
  submitButton.Attributes.Add("onclick", "if( !confirm('Are you sure you want to submit?') ) { return false; }");
}

If you’re not using the Form Designer, add the following code directly to the OnClientClick property of the button:

<asp:Button id="submitButton" text="Submit" runat="server" OnClientClick="if( !confirm('Are you sure you want to submit?') ) { return false; }"></asp:Button>

Method 2

To execute more complex script on the submit button click event, we suggest adding a function to the <script> element of your web form. The following is an example using the Form Designer.

In the form configuration Web references tab, add:

<script type="text/javascript">
function myConfirmFunction(){
  // More complex JavaScript code
  // ...
  return confirm('Are you sure you want to submit?');
}
</script>

Then, in the .NET code of the web form, call the new function in either the buttons OnClick property or its OnClick attribute:

protected void Page_Load(object sender, EventArgs e)
{
  base.Page_Load(sender, e);
  submitButton.OnClientClick = "if(!myConfirmFunction()) return false;";
}

Note: It is important that the OnClick event not return anything when the user confirms, because WorkflowGen will perform the client-side validation of the fields before the form is submitted. Returning true when the button is clicked will skip the WorkflowGen validation, which is why it only returns false if the user does not confirm.