Invalid postback or callback argument with EnableEventValidation=”true”

15 Dec
December 15, 2009

ASP.NET 2.0 has a feature known as Event Validation, which ensures that the data being sent back to the server on postback is an expected value.  Event Validation is designed to help prevent injection attacks from users who are trying to POST malicious data.  If an incoming value is returned via POST that the runtime believes is false then you will get the following exception:

“Invalid postback or callback argument. Event validation is enabled using <pages enableeventvalidation=”true” /> in configuration or <%@ page enableeventvalidation=”true” %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.”

You can easily stop this error occurring by setting EnableEventValidation = false in either your web.config (to affect the whole site) or per page.  However this opens your page to possible script injection attacks, so let’s look at some methods for finding the underlying cause of the problem first.

1. Check your data!

A common cause of this issue is when you are populating a dropdownlist with data from your database, and your data includes a carriage return or other non-text data.  Try querying your data and see if it appears valid, or if there are control or html characters that may cause an exception.

2. Are you using Javascript to populate dropdownlists?

If so you are populating server controls with client side data (eg, via Javascript) then you need to let ASP.NET know that the values you are adding are legal or you will get the above exception.  You do this by overriding the Render method of your web form:

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
   Page.ClientScript.RegisterForEventValidation(ddl1.UniqueID, "New Text")
End Sub
This code registers that the dropdownlist ddl1 is being populated with the value “New Text” via Javascript or DHTML.  Details of the RegisterForEventValidation method are here.

3. Are your users submitting your form before the EVENTVALIDATION field has rendered?

ASP.NET validates your users input against a hidden EVENTVALIDATION field.  If your network connection is slow, then the field may not have been completely rendered before the user submits the form.  Try encasing your control into an Ajax UpdatePanel to work around this.

Hope this helps.

Tags: ,
© Copyright - Evonet