Writing here to describe what is event validation in Asp.Net. Once during development I got below error when I was trying do post back using selected index Change event of a DropDown and I know you might have somewhere got this during development.
Event Validation In
You might have come across below errors.
“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.”
I solved this by setting EnableEventValidation to false in
page directive. But I was not knowing the reason why I anyone need to set this to
false and what it means.
Event validation is the new feature introduced in Asp.Net. It
checks for valid postbacks and there by disallowing any script injection
attacks and bad post backs (done by malicious users).
To discuss let’s consider an example. I have a page
page1.aspx which has following code on it.
<form id="form1" runat="server">
<asp:DropDownList ID="ddlSelectBx" runat="server" AutoPostBack="true">
<asp:ListItem Text="ONE" Value="1"></asp:ListItem>
<asp:ListItem Text="TWO" Value="2"></asp:ListItem>
<asp:ListItem Text="THREE" Value="3"></asp:ListItem>
When this page is rendered at client side you will find a
hidden field like below in in source file. (view source for the page)
This hidden field value maintains all possible postbacks
which dropdown list may cause with rendered values. It does this by hashing
controls unique id with index of listitems of dropdowns. It means postbacks
which might be caused by values ONE,TWO or THREE are already known to the runtime. When such postback happens, runtime checks to see whether this postback is valid
using de-serialized value of __EVENTVALIDATION hidden field.
Now say you have added 4th listitem to dropdown at clientside
<asp:ListItem Text="FOUR" Value="4"></asp:ListItem>
In this case runtime do not know the new item added because
it is not rendered from server but added at client side. Postback caused by such
item is not registered and not added in __EVENTVALIDATION hidden field.
When such item raises any event Event validation fails and
we get the error mentioned above.
This can be solved by ClientScript.RegisterForEventValidation
method. Write it in Page Render method.
You can tern on/off Event validation in page directive using
<%@ Page Language="C#"
Inherits="WebApplication1.Page1" EnableEventValidation="true" %>
When EnableEventValidation is false __EVENTVALIDATION hidden
field will not be rendered.