Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation=“true”/>'

StackOverflow https://stackoverflow.com/questions/228969

Question

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
Was it helpful?

Solution

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.

OTHER TIPS

Do you have codes in you Page_Load events? if yes, then perhaps by 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 will be Page_Load -> Click on Command -> Page_Load (again) -> Process ItemCommand Event

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 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 changed several codes, and finally I succeeded. My experience route:

1) 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)

2) 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);
            }
        }
    }
}

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.

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.

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.

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.

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);
}

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).

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.

(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:

http://www.c-sharpcorner.com/Forums/Thread/35301/

you try something like that,in your .aspx page

add

EnableEventValidation="false"

you feel free to ask any question!

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;"

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> 

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.

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" />

I've had the same problem, what I did:

Just added a condition if(!IsPostBack) and it works fine :)

This error will show without postback

Add code:

If(!IsPostBack){

 //do something

}

In this case add id to the button in RowDataBound of the grid. It will solve your problem.

A simple solution for this problem is to use the IsPostBack check on your page load. That will solve this problem.

Ajax UpdatePanel makes it, and I think it's the easiest way, ignoring the Ajax postback overhead.

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:

  1. Implement the ICallbackEventHandler on your page
  2. Call ClientScriptManager.GetCallbackEventReference to call your server side code
  3. 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.

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.

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!

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!!!

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>");
}

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

If you are using Ajax update panel. Add <Triggers> tag and inside it trigger the Button or control causing the postBack using <asp:PostBackTrigger .../>

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.

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!!!

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+

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top