views:

43252

answers:

20

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
+12  A: 

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.

norbertB
Thanks for the suggestions.Since I am doing an Intranet application, the quickest thing to do for now is Disable it.
J Angwenyi
+5  A: 

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.

Andy C.
+2  A: 

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

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.

My solution was to give up on nesting buttons within the datagrid. MS fails me yet again.
Repo Man
Link Button worked for me too
Marsharks
A: 

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

A: 

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

netseng
+1  A: 

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.

brian welch
The crux of this issue is the asp.net eventvalidation model and whether the "page" is modified by the client at the point when you do a post back.What do you mean '.....And these shifting controls make .net uneasy' ??
J Angwenyi
A: 

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.

Boog
this is good one. thanks
J Angwenyi
A: 

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

A: 

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

rupesh
+1  A: 

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.

Umar Farooq Khawaja
I had this exact problem with a legacy web control. Our web platform / CMS (sitecore) got a big update which turned on event validation (it had previously been off! Ouch!).The repeater control was displaying images in a web gallery (with buttons to rearrange them) and on postback of these buttons the exception would occur. I disabled view state on the repeaters using EnableViewState="false" as you suggested and hey presto it worked. As others have found, Overriding Render() and using ClientScriptManager.RegisterForEventValidation() didn't work for me. THANK YOU!
xan
A: 

There is a good article on EventValidation at

Invalid postback or callback argument with EnableEventValidation="true"

Bartek
A: 

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

Sumaira
super dude it is working fine thank you
Surya sasidhar
A: 

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

Razia
A: 

Well, after reading all these answers given by all these experts I tried the simplest one that is IsPostBack method. It worked very well for me. Thanks to all of you, especially Sumaira!

Dheeraj
+1  A: 

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!

cem
A: 

Do

EnableEventValidation="false" 

in the first line of the .aspx file. The problem will be solved.

hrushikesh
A: 

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

Jeff Pang
A: 

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

batsuuri
A: 

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>");
            }
Murad Dodhiya
A: 

I think if you change the type of button, the problem will be solved