How to use ClientScriptManager.RegisterForEventValidation method
Wednesday, December 9th, 2009Have you ever encountered this error:
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.
That’s pretty long error message. I get this exception if I add items to drop-down control from JavaScript. The question is how to use ClientScriptManager.RegisterForEventValidation method?
First, let’s reproduce the problem. Create a new website and copy/paste this code:
<asp:DropDownList ID="dd" runat="server">
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Two</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Test" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(function()
{
$("#<%= dd.ClientID %>").append($("<option />")
.val(3)
.text("Three!"));
});
</script>
If you select option “Three” sure enough, exception is thrown. To prevent it you need to supply all possible values for drop-down control:
protected override void Render(HtmlTextWriter writer)
{
Page.ClientScript.RegisterForEventValidation(dd.UniqueID, "3");
Page.ClientScript.RegisterForEventValidation(dd.UniqueID, "4");
Page.ClientScript.RegisterForEventValidation(dd.UniqueID, "11");
// and so on
base.Render(writer);
}
The exception is fixed but server variable for drop-down control is useless – it has no idea that you’ve added new item so dd.SelectedValue will give One, not 3. You need to read POST variable directly instead, like this:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
Response.Write(Request.Form[dd.UniqueID]);
}


