This is a quick demo showing how to prompt the user to confirm when submitting a form on an ASP.Net page. We start with a simple form.

There is some server side code which will populate a label with the current date and time when the form is submitted.
protected void SubmitButton_Click(object sender, EventArgs e)
{
Timestamp.Text = DateTime.Now.ToString();
}
If the user is simply required to confirm the submitting of the form then an OnClientClick action can be specified.
<asp:Button runat="server" ID="SubmitButton" Text="Submit" CssClass="btn btn-default" OnClientClick="return confirm('Do you want to submit this page?')" CausesValidation="false" OnClick="SubmitButton_Click" />
When the form is submitted it will display the confirmation prompt.

If the Cancel button is pressed the form will not be submitted. If the OK button is pressed the form will be submitted and the current date and time will be displayed in a label.

The form in this example very simple. In a real application forms are usually more complicated with fields that require validation. Suppose we only want to prompt the user to confirm the form submission if the form is validated. This is still simple to do with very minor changes, the trick is to check the status of the validation on the client side first by calling the Page_ClientValidate method.
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="Name" CssClass="col-md-2 control-label">Name</asp:Label>
<div class="col-md-10">
<asp:TextBox runat="server" ID="Name" CssClass="form-control" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="Name" CssClass="text-danger" ErrorMessage="Name is required." />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<asp:Button runat="server" ID="SubmitButton" Text="Submit" CssClass="btn btn-default" OnClientClick="if (Page_ClientValidate()){return confirm('Do you want to submit this page?')}" CausesValidation="false" OnClick="SubmitButton_Click" />
</div>
</div>
With this code the form is not valid until the Name textbox contains a value. Only when all the validation controls are valid will the Confirm prompt be displayed. As before, if the Cancel button is pressed the form will not be submitted. If the OK button is pressed the form will be submitted and the current date and time will be displayed in a label.











You must be logged in to post a comment.