When does it come up? What we can do to eliminate this exception due coding mistakes?
As I have already spoken about the script injection attack can cause this exception, we should not bother about why it is coming up. Rather in that case we can track down the client who is trying to inject the attack and take appropriate action. So I will rather focus upon the scenarios when it comes up due some coding mistakes.
These mistakes are many in number so I would rather cover just a couple of them in this Post:
1. You have migrated an ASP.NET application from version 1.1. In 1.1 we had to manipulate the "Select" button column for selecting the record and we normally set the visible property of this button column to FALSE.
The button column has "LinkButton" /”Button” for selecting records and we manually do a Postback using the __dopostback() method.
Agreed that the "LinkButton" /”Button” should register this method for event validation by internally calling the ClientScript.RegisterForEventValidation(). But with the “Visible” property set to FALSE, the control is not rendered and therefore control is not registered for EventValidation by ASP.NET 2.0. However, the DataGrid still utilizes this event. Since the event is not registered, it results in the above error.
In this scenario manually registering the client script for each DataGrid rows will help.
You can simply loop through the rows as mentioned in below code.
protected override void Render(HtmlTextWriter writer)
{
foreach (DataGridItem row in DataGrid1.Items)
ClientScript.RegisterForEventValidation(row.UniqueID.ToString() +":_ctl0");
base.Render(writer);
}
So this signifies that if you are not rendering the control then it is not registered for the validation internally. You need to do that manually using the RegisterForEventValidation function.
2. You have an ASP.NET 2.0 or above application which has a page with a lot of Javacript adding dynamic controls. On the POST of this particular page you will get the above mentioned exception for Invalid Postback or callback argument. This happens if Javascript is adding a FORM tag as well as adding dynamic controls resulting in the nested form Tags.
This can be reproduced quite easily as well –
In Default.aspx have the below code –
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" />
<form></form>
</div>
</form>
</body>
</html>
So this signifies that if you have nested form tags the above mentioned error message will come up.