Disabling Validation


Typically, a form includes a Cancel button that enables you to stop working on the form and navigate to a new page. Implementing a Cancel button in a form that includes validation controls, however, is more difficult than you might expect. The problem is that the client-side validation scripts can prevent any subroutine associated with the Cancel button from ever executing.

To get around this problem, you need to use a special property of the Button , LinkButton , and ImageButton controls named the CausesValidation property. You can use the CausesValidation property to enable or disable validation when a particular button is clicked.

For example, the page in Listing 3.21 contains both a Submit and Cancel button. The CausesValidation property is assigned the value False in the case of the Cancel button.

Listing 3.21 CausesValidation.a spx
 <Script runat="Server"> Sub btnSubmit_Click( s As Object, e As EventArgs )   If IsValid Then     Response.Redirect( "ThankYou.aspx" )   End If End Sub Sub btnCancel_Click( s As Object, e As EventArgs )   Response.Redirect( "Cancel.aspx" ) End Sub </Script> <html> <head><title>CausesValidation.aspx</title></head> <body> <form runat="Server"> Enter your first name: <br> <asp:TextBox   id="txtFirstName"   Runat="Server" /> <asp:RequiredFieldValidator   ControlToValidate="txtFirstName"   Text="Required!"   Runat="Server" /> <p> <asp:Button   id="btnSubmit"   Text="Submit"   OnClick="btnSubmit_Click"   Runat="Server" /> <asp:Button   id="btnCancel"   Text="Cancel"   OnClick="btnCancel_Click"   CausesValidation="False"   Runat="Server" /> </form> </body> </html> 

The C# version of this code can be found on the CD-ROM.p



ASP.NET Unleashed
ASP.NET 4 Unleashed
ISBN: 0672331128
EAN: 2147483647
Year: 2003
Pages: 263

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net