[.net] Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

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

This question is related to .net asp.net .net-2.0 postback argumentexception

The answer is


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


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


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.


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.


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

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


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


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


you try something like that,in your .aspx page

add

EnableEventValidation="false"

you feel free to ask any question!


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

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


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

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.


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

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!


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.


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.


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


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


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


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.


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


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


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.


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

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


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.


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


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

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


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>

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.


This error will show without postback

Add code:

If(!IsPostBack){

 //do something

}

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+


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.


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+


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.


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.


Check you data of binded your controls. Some invalid data corrupt ValidateEvent.


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


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.


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


This error will show without postback

Add code:

If(!IsPostBack){

 //do something

}

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>

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

you try something like that,in your .aspx page

add

EnableEventValidation="false"

you feel free to ask any question!


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.


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

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


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

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> 

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.


Check you data of binded your controls. Some invalid data corrupt ValidateEvent.


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


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.


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.


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


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

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.


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.


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.


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.


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've had the same problem, what I did:

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


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.


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!


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


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

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

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


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


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.


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.


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.


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.


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


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


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


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> 

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to .net-2.0

"This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded" Debugging doesn't start How to show text in combobox when no item selected? Compression/Decompression string with C# Best way to Bulk Insert from a C# DataTable Get domain name How to open a new form from another form Maximize a window programmatically and prevent the user from changing the windows state How should you diagnose the error SEHException - External component has thrown an exception Editing dictionary values in a foreach loop

Examples related to postback

Confirm postback OnClientClick button ASP.NET A potentially dangerous Request.Form value was detected from the client Forcing a postback Retrieving data from a POST method in ASP.NET How to use __doPostBack() OnclientClick and OnClick is not working at the same time? ASP.NET postback with JavaScript jQuery UI Dialog with ASP.NET button postback Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

Examples related to argumentexception

How to check if a column exists in a datatable "Parameter not valid" exception loading System.Drawing.Image Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'