Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'
.Netasp.net.Net 2.0PostbackArgumentexception.Net Problem Overview
I am getting the following error when I post back a page from the client-side. I have JavaScript code that modifies an asp:ListBox on the client side.
How do we fix this?
Error details below:
Server Error in '/XXX' Application.
--------------------------------------------------------------------------------
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.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: 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.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: 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.]
System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +2132728
System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108
System.Web.UI.WebControls.ListBox.LoadPostData(String postDataKey, NameValueCollection postCollection) +274
System.Web.UI.WebControls.ListBox.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +11
System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +353
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1194
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
.Net Solutions
Solution 1 - .Net
Do you have code in your Page_Load events? if yes, then perhaps adding the following will help.
if (!Page.IsPostBack)
{ //do something }
This error is thrown when you click on your command and the Page_load is being ran again, in a normal life cycle it would be Page_Load -> Click on Command -> Page_Load (again) -> Process ItemCommand Event
Solution 2 - .Net
The problem is that ASP.NET does not get to know about this extra or removed listitem. You got an number of options (listed below):
- Disable eventvalidation (bad idea, because you lose a little of security that come with very little cost).
- Use ASP.NET Ajax UpdatePanel. (Put the listbox in the Updatepanel and trigger a update, if you add or remove listbox. This way viewstate and related fields get updates and eventvalidation will pass.)
- Forget client-side and use the classic postback and add or remove the listitems server-side.
I hope this helps.
Solution 3 - .Net
I had an experience with DataGrid. One of it's columns was "Select" button. When I was clicking "Select" button of any row I had received this error message:
>"Invalid postback or callback argument. Event validation is enabled using
I changed several codes, and finally I succeeded. My experience route:
-
I changed page attribute to
EnableEventValidation="false"
. But it didn't work. (not only is this dangerous for security reason, my event handler wasn't called:void Grid_SelectedIndexChanged(object sender, EventArgs e)
-
I implemented
ClientScript.RegisterForEventValidation
in Render method. But it didn't work.protected override void Render(HtmlTextWriter writer) { foreach (DataGridItem item in this.Grid.Items) { Page.ClientScript.RegisterForEventValidation(item.UniqueID); foreach (TableCell cell in (item as TableRow).Cells) { Page.ClientScript.RegisterForEventValidation(cell.UniqueID); foreach (System.Web.UI.Control control in cell.Controls) { if (control is Button) Page.ClientScript.RegisterForEventValidation(control.UniqueID); } } } }
-
I changed my button type in grid column from
PushButton
toLinkButton
. It worked! ("ButtonType="LinkButton"). I think if you can change your button to other controls like "LinkButton" in other cases, it would work properly.
Solution 4 - .Net
You are really going to want to do 2 or 3, don't disable event validation.
There are two main problems with adding items to an asp:listbox client side.
-
The first is that it interferes with event validation. What came back to the server is not what it sent down.
-
The second is that even if you disable event validation, when your page gets posted back the items in the listbox will be rebuilt from the viewstate, so any changes you made on the client are lost. The reason for this is that a asp.net does not expect the contents of a listbox to be modified on the client, it only expects a selection to be made, so it discards any changes you might have made.
The best option is most likely to use an update panel as has been recommended. Another option, if you really need to do this client side, is to use a plain old <select>
instead of an <asp:ListBox>
, and to keep your list of items in a hidden field. When the page renders on the client you can populate it from a split of your text field contents.
Then, when you are ready to post it, you repopulate the hidden field's contents from your modified <select>
. Then, of course, you have to split that again on the server and do something with your items, since your select is empty now that it's back on the server.
All in all it's a pretty cumbersome solution that I would not really recommend, but if you really have to do client-side modifications of a listBox, it does work. I would really recommend you look into an updatePanel before going this route, however.
Solution 5 - .Net
None of the above worked for me. After more digging I realized I had overlooked 2 forms applied on the page which was causing the issue.
<body>
<form id="form1" runat="server">
<div>
<form action="#" method="post" class="form" role="form">
<div>
...
<asp:Button ID="submitButton" runat="server"
</div>
</div>
</body>
Be aware that recently ASP.NET has started considering iframes within a form tag which contains a form tag in the iframe document itself a nested frame. I had to move the iframe out of the form tag to avoid this error.
Solution 6 - .Net
I had the same problem with a Repeater because I had a web-page with a Repeater control in a web-site which had EnableEventValidation switched on. It wasn't good. I was getting invalid postback related exceptions.
What worked for me was to set EnableViewState="false" for the Repeater. The advantages are that it is simpler to use, as simple as switching event validation off for the web-site or web-page, but the scope is a lot less than switching event validation off for either.
Solution 7 - .Net
I had the same problem when modifying a ListBox using JavaScript on the client. It occurs when you add new items to the ListBox from the client that were not there when the page was rendered.
The fix that I found is to inform the event validation system of all the possible valid items that can be added from the client. You do this by overriding Page.Render and calling Page.ClientScript.RegisterForEventValidation for each value that your JavaScript could add to the list box:
protected override void Render(HtmlTextWriter writer)
{
foreach (string val in allPossibleListBoxValues)
{
Page.ClientScript.RegisterForEventValidation(myListBox.UniqueID, val);
}
base.Render(writer);
}
This can be kind of a pain if you have a large number of potentially valid values for the list box. In my case I was moving items between two ListBoxes - one that that has all the possible values and another that is initially empty but gets filled in with a subset of the values from the first one in JavaScript when the user clicks a button. In this case you just need to iterate through the items in the first ListBoxand register each one with the second list box:
protected override void Render(HtmlTextWriter writer)
{
foreach (ListItem i in listBoxAll.Items)
{
Page.ClientScript.RegisterForEventValidation(listBoxSelected.UniqueID, i.Value);
}
base.Render(writer);
}
Solution 8 - .Net
you try something like that,in your .aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="abc.aspx.cs" Inherits="yourProjName.yourDirectory.abc" MasterPageFile="~/MasterPage/MainMaster.Master" EnableEventValidation="false"%>
add
> EnableEventValidation="false"
you feel free to ask any question!
Solution 9 - .Net
One other way not mentioned here is to subclass ListBox
Ie.
public class ListBoxNoEventValidation : ListBox
{
}
ClientEventValidation keys off the attribute System.Web.UI.SupportsEventValidation if you subclass it, unless you explicitly add it back in, it will never call the validation routine. That works with any control, and is the only way I've found to "disable" it on a control by control basis (Ie, not page level).
Solution 10 - .Net
If you fill the DropdownList through client side script then clear the list before submit the form back to server; then ASP.NET will not complain and the security will be still on.
And to get the data selected from the DDL, you can attach an "OnChange" event to the DDL to collect the value in a hidden Input or in a textbox with Style="display: none;"
Solution 11 - .Net
> 3: I changed my button type in grid > column from "PushButton" to > "LinkButton". It worked! > ("ButtonType="LinkButton") I think if > you can change your button to other > controls like "LinkButton" in other > cases, it would work properly.
I wish I could vote you up, Amir (alas my rep is too low.) I was just having this problem and changing this worked like a champ on my gridview. Just a little aside, I think the valid code is: ButtonType="Link"
I suspect this is because when you click 'edit', your edit changes to 'update' and 'cancel' which then change back to 'edit' on submit. And these shifting controls make .net uneasy.
Solution 12 - .Net
(1) EnableEventValidation="false"...................It does not work for me.
(2) ClientScript.RegisterForEventValidation....It does not work for me.
Solution 1:
Change Button/ImageButton to LinkButton in GridView. It works. (But I like ImageButton)
Research: Button/ImageButton and LinkButton use different methods to postback
Original article:
http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
Solution 2:
In OnInit() , enter the code something like this to set unique ID for Button/ImageButton :
protected override void OnInit(EventArgs e) {
foreach (GridViewRow grdRw in gvEvent.Rows) {
Button deleteButton = (Button)grdRw.Cells[2].Controls[1];
deleteButton.ID = "btnDelete_" + grdRw.RowIndex.ToString();
}
}
Original Article:
Solution 13 - .Net
I implemented a nested grid view and i faced the same problem .I have used LinkButton instead of image button like this:
before i had a column like this:
<asp:TemplateField ItemStyle-Width="9">
<ItemTemplate>
<asp:ImageButton ID="ImgBtn" ImageUrl="Include/images/gridplus.gif" CommandName="Expand"
runat="server" />
</ItemTemplate>
</asp:TemplateField>
I have replaced like this.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton CommandName="Expand" ID="lnkBtn" runat="server" ><asp:Image ID="Img" runat="server" ImageUrl="~/Images/app/plus.gif" /></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Solution 14 - .Net
I had a similar issue, but I was not using ASP.Net 1.1 nor updating a control via javascript. My problem only happened on Firefox and not on IE (!).
I added options to a DropDownList on the PreRender event like this:
DropDownList DD = (DropDownList)F.FindControl("DDlista");
HiddenField HF = (HiddenField)F.FindControl("HFlista");
string[] opcoes = HF.value.Split('\n');
foreach (string opcao in opcoes) DD.Items.Add(opcao);
My "HF" (hiddenfield) had the options separated by the newline, like this:
HF.value = "option 1\n\roption 2\n\roption 3";
The problem was that the HTML page was broken (I mean had newlines) on the options of the "select" that represented the DropDown.
So I resolved my my problem adding one line:
DropDownList DD = (DropDownList)F.FindControl("DDlista");
HiddenField HF = (HiddenField)F.FindControl("HFlista");
string dados = HF.Value.Replace("\r", "");
string[] opcoes = dados.Split('\n');
foreach (string opcao in opcoes) DD.Items.Add(opcao);
Hope this help someone.
Solution 15 - .Net
if you change UseSubmitBehavior="True"
to UseSubmitBehavior="False"
your problem will be solved
<asp:Button ID="BtnDis" runat="server" CommandName="BtnDis" CommandArgument='<%#Eval("Id")%>' Text="Discription" CausesValidation="True" UseSubmitBehavior="False" />
Solution 16 - .Net
I've had the same problem, what I did:
Just added a condition if(!IsPostBack)
and it works fine :)
Solution 17 - .Net
This error will show without postback
Add code:
If(!IsPostBack){
//do something
}
Solution 18 - .Net
Ajax UpdatePanel makes it, and I think it's the easiest way, ignoring the Ajax postback overhead.
Solution 19 - .Net
In this case add id to the button in RowDataBound of the grid. It will solve your problem.
Solution 20 - .Net
A simple solution for this problem is to use the IsPostBack check on your page load. That will solve this problem.
Solution 21 - .Net
We ran into this same issue when we were converting our regular ASPX pages to Content pages.
The page with this issue had a </form>
tag within one of the Content sections, thus two form end tags were rendered at run time which caused this issue. Removing the extra form end tag from the page resolved this issue.
Solution 22 - .Net
I know that this is a super-old post. Assuming that you are calling into your application, here is an idea that has worked for me:
- Implement the ICallbackEventHandler on your page
- Call ClientScriptManager.GetCallbackEventReference to call your server side code
- As the error message states, you could then call ClientScriptManager.RegisterForEventValidation
If you don't need total control, you could use an update panel which would do this for you.
Solution 23 - .Net
If you are using gridview and not bind gridview at pageload inside !ispostback then this error occur when you click on edit and delete row in gridview .
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridview();
}
Solution 24 - .Net
I was using datalist and I was getting the same error for my push button. I just use IsPostBack to check and fill my controls and the problem is solved! Great!!!
Solution 25 - .Net
Four minutes ago I received the same error. Then I have researched during one half hour like you. In all forums they are generally saying "add page enableEvent..=false or true". Any solution proposed didn't resolved my problems until I found it. The problem is unfortunately an ASP.NET button. I removed it two seconds ago. I tried to replace with "imagebutton", but it was also unacceptable (because it gave the same error).
Finally I have replaced with LinkButton
. it seems to be working!
Solution 26 - .Net
What worked for me is moving the following code from page_load to page_prerender:
lstMain.DataBind();
Image img = (Image)lstMain.Items[0].FindControl("imgMain");
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
cs.RegisterStartupScript(cstype, csname1, "<script language=javascript> p=\"" + img.ClientID + "\"</script>");
}
Solution 27 - .Net
If you are using Ajax update panel. Add <Triggers>
tag and inside it trigger the Button or control causing the postBack using <asp:PostBackTrigger .../>
Solution 28 - .Net
Best option to do is use hidden field and do not disable event validation, also change every listbox, dropdownlist to select with runat server attribute
Solution 29 - .Net
If you know up front the data that could be populated, you can use the ClientScriptManager to resolve this issue. I had this issue when dynamically populating a drop down box using javascript on a previous user selection.
Here is some example code for overriding the render method (in VB and C#) and declaring a potential value for the dropdownlist ddCar.
In VB:
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
Dim ClientScript As ClientScriptManager = Page.ClientScript
ClientScript.RegisterForEventValidation("ddCar", "Mercedes")
MyBase.Render(writer)
End Sub
or a slight variation in C# could be:
protected override void Render(HtmlTextWriter writer)
{
Page.ClientScript.RegisterForEventValidation("ddCar", "Mercedes");
base.Render(writer);
}
For newbies: This should go in the code behind file (.vb or .cs) or if used in the aspx file you can wrap in <script>
tags.
Solution 30 - .Net
This was the reason why I was getting it:
I had an ASP:ListBox. Initially it was hidden. At client side I would populate it via AJAX with options. The user chose one option. Then when clicking the Submit button, the Server would get all funny about the ListBox, since it did not remember it having any options.
So what I did is to make sure I clear all the list options before submitting the form back to the server. That way the server did not complain since the list went to the client empty and it came back empty.
Sorted!!!
Solution 31 - .Net
As Nick B said and that worked for me you have to remove line breaks in some cases. Take a look at the code:
-Wrong way:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Selected="True">
Item 1</asp:ListItem>
<asp:ListItem>
Item 2</asp:ListItem>
<asp:ListItem>
Item 3</asp:ListItem>
</asp:DropDownList>
-Right way:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Selected="True">Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
</asp:DropDownList>
It only ocurred for me in IE10+
Solution 32 - .Net
After having this problem on remote servers (production, test, qa, staging, etc), but not on local development workstations, I found that the Application Pool was configured with a RequestLimit other than 0.
This caused the app pool to give up and reply with the exception noted in the question.
Solution 33 - .Net
For us the problem was happening randomly only in the production environment. The RegisterForEventValidation did nothing for us.
Finally, we figured out that the web farm in which the asp.net app was running, two IIS servers had different .net versions installed. So it appears they had different rules for encrypting the asp.net validation hash. Updating them solved most of the problem.
Also, we configured the machineKey(compatibilityMode) (the same in both servers), httpRuntime(targetFramework), ValidationSettings:UnobtrusiveValidationMode, pages(renderAllHiddenFieldsAtTopOfForm) in the web.config of both servers.
We used this site to generate the key https://www.allkeysgenerator.com/Random/ASP-Net-MachineKey-Generator.aspx
We spent a lot of time solving this, I hope this helps somebody.
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
...
</appSettings>
<system.web>
<machineKey compatibilityMode="Framework45" decryptionKey="somekey" validationKey="otherkey" validation="SHA1" decryption="AES />
<pages [...] controlRenderingCompatibilityVersion="4.0" enableEventValidation="true" renderAllHiddenFieldsAtTopOfForm="true" />
<httpRuntime [...] requestValidationMode="2.0" targetFramework="4.5" />
...
</system.web>
Solution 34 - .Net
I worked around this exact error by not adding the ListBox to a parent Page/Control Controls collection. Because I really didn't need any server-side functionality out of it. I just wanted to use it to output the HTML for a custom server control, which I did in the OnRender event handler myself. I hoped that using the control would save me from writing to the response my own html.
This solution probably won't work for most, but it keeps ASP.NET from performing the ValidateEvent against the control, because the control doesn't retain in memory between postbacks.
Also, my error was specifically caused by the selected list item being an item that wasn't in the listbox the previous postback. Incase that helps anyone.
Solution 35 - .Net
When I added the id on ItemDataBound then it did not give me the error, but it was not giving me the command name. It was returning command name empty. Then I added command name as well while ItemDataBound. Then it resolved the same problem. Thanks Nilesh, great suggestion. It Worked :)
Solution 36 - .Net
I had the same problem, two list boxes and two buttons.
The data in the list boxes was being loaded from a database and you could move items between boxes by clicking the buttons.
I was getting an invalid postback.
turns out that it was the data had carriage return line feeds in it which you cannot see when displayed in the list box.
worked fine in every browser except IE 10 and IE 11.
Remove the carriage return line feeds and all works fine.
Solution 37 - .Net
FYI I had the same issue with that error message and it was that I had 2 form tags on the same page. There was one in the Master page and one in the page itself. Soon as I removed the second form tag pair the problem went away.
Solution 38 - .Net
The following example shows how to test the value of the IsPostBack property when the page is loaded in order to determine whether the page is being rendered for the first time or is responding to a postback. If the page is being rendered for the first time, the code calls the Page.Validate method. The page markup (not shown) contains RequiredFieldValidator controls that display asterisks if no entry is made for a required input field. Calling Page.Validate causes the asterisks to be displayed immediately when the page is rendered, instead of waiting until the user clicks the Submit button. After a postback, you do not have to call Page.Validate, because that method is called as part of the Page life cycle.
private void Page_Load()
{
if (!IsPostBack)
{
}
}
Solution 39 - .Net
My problem was solved when cancel event at end of grid event at server side.
protected void grdEducation_RowEditing(object sender, GridViewEditEventArgs e)
{
// do your processing ...
// at end<br />
e.Cancel = true;
}
Solution 40 - .Net
Check you data of binded your controls. Some invalid data corrupt ValidateEvent.