Tuesday, March 14, 2006 - Posts

Client Side ''onsubmit'' Action

There are two ways to add some client-side processing before ASP.NET 2.0 page submitted.
1. Add onsubmit attribute to Form tag in aspx file
2. Use this.Page.ClientScript.RegisterOnSubmitStatement method
Is there any difference?
The answer is processing order.
When aspx page being processed internal collection (_registeredOnSubmitStatements) created which holds all submit statements in order of RegisterOnSubmitStatement calls. Value of onsubmit attribute from aspx added at the end. Client side script created from this collection as statements of WebForm_OnSubmit function.
Now, when the order is particulary importemnt? It will be if we will use validator controls. Validator controls that allows client side script also register submit statement (through BaseValidator class) at PreRender stage. If client side validation fails, any submit statement that follows will not be executed. This behavior is very useful in some scenarios but unwanted in others.
The suggestion is:
- If you need to execute client script on page submit regardless of validation result (submit attempt), use RegisterOnSubmitStatement method before PreRender (for example in Page_Load).
- If you want to execute script only after successful validation, use onsubmit attribute.