Thursday, November 9, 2006

RegisterForEventValidation and event validation

When submitting pages in ASP.NET 2.0 you may get a validation error.

"Invalid postback or callback argument.
Description: An unhandled exception occurred during the execution of the current web request. "

Event validation is enabled using in configuration or <%@ Page> EnableEventValidation="true" %> in a page

For security purposes it is not advisable to turn off validation.

The error occurs for one of the following reasons:

1) You have a server-side asp control (such as a drop down) that you populate using javascript. The server-side rendered values do not match the populated values since you populated the drop down on the client-side.

2) You have an invalid HTML on the page. (For example, you may have a closing /form tag without a corresponding beginning form tag!). You may want to run your HTML through one of many free HTML validators on the Internet.


In the first case where you have populated your drop down with Javascript you could eliminate the error by calling the RegisterForEventValidation function. RegisterForEventValidation can only be called during Render().
You will need to register each valid value that you use in the Javascript code. For example if you populate a drop down with U.S. state abbreviations, you need to register each state code on the server side as follows:

Page.ClientScript.RegisterForEventValidation(ddlState.UniqueID, "AK");
Page.ClientScript.RegisterForEventValidation(ddlState.UniqueID, "AL");
Page.ClientScript.RegisterForEventValidation(ddlState.UniqueID, "CA");

And so forth ...


You may also want to consider the following as another workaround:
(Check the following article for more details: http://msdn2.microsoft.com/en-us/library/w1sw53ds.aspx)

1)If you want to display strings in your application but do not trust them, apply HTML encoding to them when the strings are written back in a response. For example, with encoding, the tag b becomes <b>. You might do this if the strings that you are displaying are from a database whose contents you are not sure that you can trust.

2)If you want your application to accept some HTML (for example, some formatting instructions from users), you should encode the HTML at the client before it is submitted to the server.





@Copyright 2006, Isaac Levy

No comments: