Wednesday, March 16, 2011

How to deal with ASP.NET Event Validation

I have encountered problems with the Event Validation mechanism in ASP.NET when I add values to a dropdown list using javascript - in this case I sometimes get an exception. How to deal with it? I found several solutions on the web, but none were very good. While this mechanism can be disabled, it is not good to do so for application secruity reasons. I found another solution which worked great for me:
First you must understand why the exception occured: It is because the value selected by the user did not exist in the original values in the drop-down list as originally created by the server. So what I did was to create a hidden field, and send the value to the server in the hidden field (put the selected value in a hidden field on the client using javascript). And, right before the postback (on the client using javacript), disable the drop-down element. Disabling this element prevents its value from being sent to the server, thus preventing the Event Validation exception.
Example how to disable:

var ddlProfField = document.getElementById("ddlProfessionalField");
ddlProfField.disabled = "disabled";


Another option, instead of disabling the element, is to clear its values like this:

ddlProfField.options.length = 0;

If this post helped you, please let me know by posting a comment !

For other solutions see this link: http://odetocode.com/blogs/scott/archive/2006/03/21/asp-net-event-validation-and-invalid-callback-or-postback-argument-again.aspx