Thursday 4 September 2008

Invalid Postback or callback argument. A code behind solution to this problem...

I have recently been taking my first tentative steps into the world of AJAX, and believe me, it's a mine field out there!!

A problem that was really bugging me was getting the infamous error:

Invalid Postback or callback argument . Event validation is enabled using 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.

As I did not write the code I was working with, I couldn't identify exactly which controls were causing the problem, nor did I know exactly which pages were affected. As a result adding the
EnableEventValidation="False" to the @Page tag of all the aspx files was not possible.

Luckily however, all of the pages on the site derive from a custom Page class (which inherits from System.Web.UI.Page).

This meant that I could override the EnableEventValidation property from the code behind rather than relying on finding all the page tags.

The code in the Page class goes a bit like this:

public override bool EnableEventValidation
{
get {return false;}
set {base.EnableEventValidation = value;}
}

This simply ensures that event validation is always false, regardless of what the @Page tag says!

I hope this helps someone, but it is worth pointing out one or two issues here:
  • EventValidation is a security feature added to ASP.NET 2.0 to prevent postback spoofing. Turning it off could leave your website vulnerable to injection attacks.
  • Overriding the EnableEventValidation at the base class level will ignore anything set in the @page directive. Developers may therefore believe they have told the page to do one thing and be very confused when it does not behave as expected. Event worse, they may never notice that event validation is turned off, which could pose unidentified issues when the website is live.


For more information, you could try http://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/122006-1.aspx which pointed me in the right direction for this solution. Also
http://odetocode.com/Blogs/scott/archive/2006/03/20/3145.aspx and http://odetocode.com/Blogs/scott/archive/2006/03/21/3153.aspx are very useful.

No comments: