ASP.NET Error on button click - asp.net

I am getting this error while clicking on the button control of an asp.net page.NO idea what to do
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 have EnableEventValidation="true" in my page directive

Set EnableEventValidation="false" as a starter maybe? Are you doing anything in particular on the page, anything out of the ordinary?

EnableEventValidation="false" will solve the error message.
It's usually down to javascript changing the values of list items on the page when ASP.NET expects that they will be unchanged from what was rendered on the server.
You'd probably need to post some code for people help further.

Related

Issue with __Event validation field

Hi Can someone tell me if I get the below error
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."
How can I find out which control and which page is throwing the error given that I am working with a large website having multiple pages and each page having n number of controls .

ASP.NET AJAX weirdness

Ok, I thought I understood these topics well, but I guess not, so hopefully someone here can clear this up.
Page.IsAsync seems to be broken. It always returns false.
But ScriptManager.IsInAsyncPostBack seems to work, sort of.
It returns true during the round trip for controls inside UpdatePanels. This is good; I can tell if it's a partial postback or a regular one.
ScriptManager.IsInAsyncPostBack returns false however for async Page Methods. Why is this? It's not a regular postback, I'm just calling a public static method on the page.
It causes a problem because I also realized that if you have a control with AutoPostBack = false, it won't trigger a postback on it's own, but if it has an event handler on the page, that event handler code WILL run on the next postback, regardless of how the postback occurred, IF the value has changed.
i.e. if I tweak a dropdown and then hit a button, that dropdown's handler code will fire. This is ok, except that it will also happen during Page Method calls, and I have no way to know the difference.
Any thoughts?
As Tjaart points out, Page.IsAsync has nothing to do with AJAX! See MSDN for a bit more info about IsAsync and see http://msdn.microsoft.com/en-us/magazine/cc163725.aspx for a fuller description of async pages].
Page methods are web services by a different name. The ScriptManager will emit the necessary JS boiler plate to make creating an XHR that invokes the web service very easy but that's all ScriptManager has to do with them really.
As the MSDN page states, ScriptManager.IsInAsyncPostBack will only be true if the request is in "partial rendering mode" so ScriptManager.IsInAsyncPostBack will be false when you are executing a page method because that request has not been spawned as a result of a partial postback (i.e. an UpdatePanel refreshing its contents).
Now it sounds like you are getting server side event handlers being executed as an apparent result of calling a page method from JS. AFAIAA, invoking a page method using javascript should not cause the page to go through its normal page lifecycle - so Page load, init etc. and these events should not be executing. So that is strange.
Suggestion: -
See Anz's comments and Dave's replies here encosia.
Could it be that you are having similar problems to Anz? i.e. The page method is invoked and but then your page is posting back immediatly after?
This is so because ASP.NET Ajax and ASP.NET Callbacks are two different things and are implemented differently. Unfortunately you have to use both Page.IsAsync and ScriptManager.IsInAsyncPostBack.
Page.IsASync probably returns whether the page was set as Async in the page directive
<%# Page Language="vb" Async="true" ...
The autopostback flag is so that you don't get a postback after every single control action, so the user can fill in an entire form and then only create the postback and trigger all the related code.
It's not really weirdness, they designed it this way so that the server side code will always be synchronized with the client side. So if you make a drop down list selection on the page and a postback occurs then that drop down list change executes it's own code along with the control that triggered the postback. You may want to read up more on the ASP .Net page lifecycle. it made things much more clear for me.

Invalid postback or callback argument. Debug question

I am getting the error: "Invalid postback or callback argument. Event validation is enabled using in configuration or 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." Event validation is enabled using in configuration or in a page. I am not modifying the data in controls through javascript. The error happens very infrequently and I am only aware of it due to some automatic e-mailing I have setup when exceptions are thrown. What is the best way for me to go about finding the cause of the exception? Is it possible that on occasions some text entered into a text box is causing this error and I need to be doing an Html Encode? When would I do the encode?
If the problem happens very infrequently it usually means that some user has posted a page to quickly or have a very poor connection, that does not allow all the hidden ASP.net callback javascript mechanism being in place.
I've often encountered this issue when a user submits a form with a potentially dangerous character in the field ('<', '>', etc.). If your page needs to allow these characters to be submitted in a form, you need to set the page-level property 'ValidateRequest' to false.
Ex.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="MyClass.cs" Inherits="MyClass" ValidateRequest="false" %>
If you want to block these types of submissions (which is usually advisable), you'll probably need to add client-side scripting to prevent entry of invalid characters to the form. If the user can't enter the invalid values, then the form can post successfully. If you try to do the validation only on the server-side, it won't be run because the .NET ValidateRequest happens first.
I've had this error before, it turned out someone had changed the "action" attribute of the form runat="server" tag to a different url (which doesn't work unless using cross page postbacks).
-edit: in this case ofcourse it doesn't happen infrequently, so it's probably not going to help you to the right solution

How do I prevent exceptions from half-loaded pages' form submission while using asp.net event validation?

I have a page with some dynamically added buttons. If you click a button before the page has fully loaded, it throws the classic exception:
Invalid postback or callback argument.
Event validation is enabled using in configuration or 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 am guessing the Viewstate field hasn't loaded on the form yet, the the other bits are being submitted. What's the best way to prevent this error, while maintaining Event Validation?
I answered a similar question here. To quote:
Essentially, you'll want to get the ViewState to load at the top of the page. In .NET 3.5 SP1 the RenderAllHiddenFieldsAtTopOfForm property was added to the PagesSection configuration.
Web.config
<configuration>
<system.web>
<pages renderAllHiddenFieldsAtTopOfForm="true"></pages>
</system.web>
</configuration>
Interestingly, the default value of this is true. So, in essence, if you are using .NET 3.5 SP1 then the ViewState is automatically being rendered at the top of the form (before the rest of the page is loaded) thus eliminating the ViewState error you are getting.
I've found this to be caused more often by the __EVENTVALIDATION field than the ViewState not being loaded. The __EVENTVALIDATION is at the bottom of the page and if it hasn't been received by the client when the user causes a postback you will get that exception.
I've not yet found a great solution, but what I usually do on pages that tend to cause this due to large amounts of content is to wire up the buttons to a javascript function that checks an isLoaded var that only gets set to true in the document.ready call. If isLoaded is false it silently eats the event, if it's true it lets if go through. This is a pain to set up, but it has ended most of my invalid postback issues.
What if you set those button's visible property to false by default and at the end of the page load or event validation you set their visible property to true? This way restricting them from clicking the button until the page has fully loaded.
From what I can tell the ViewState is loaded right after the form tag on the page.
Have you tried using ClientScriptManager.RegisterForEventValidation( button.UniqueID ) for each button after you add the button to the page? Depending on where you add the button, the event hookup for the page may have already happened and thus the events generated by the button may not be registered with the page.
I spent quite a long time trying to figure out why the __EVENTVALIDATION tag renders at the bottom on a particular site but towards the top on every other website. I eventually figured out it was because of code in the Render override event. That, along with a lean viewstate mostly got rid of this error but just for good measure I added the logic below on the button that was causing the error:
javascript somewhere on the page
function CheckForHiddenFields()
{
var EventValidation = document.getElementById('__EVENTVALIDATION');
if (EventValidation && EventValidation.value && EventValidation.value != '')
{
return true;
}
else
{
return false;
}
}
Add attribute to asp:Button:
OnClientClick="return CheckForHiddenFields();"

ViewState error points in site.master

I just added asp.net calendar control in new page under sample folder in asp.net mvc beta application. when i execute the particaular page that i need and it shows the error following
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
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.
that points to here . It's in site.master of asp.net mvc
<div id="logindisplay">
<% Html.RenderPartial("LoginUserControl"); %>
</div>
usually to avoid this error, we give
<pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" >
but, it doesn't work for me.
Before reading further, please exclude the following preconditions:
You aren't using a web farm.
It appears when using built-in databound controls such as GridView, DetailsView or FormView which utilize “DataKeyNames”.
It appears if you have a large page which loads slowly for any reason.
If following preconditions are true and you click a postbacking control/link and the page hasn't loaded completely in client browser, you might get the "Validation of ViewState MAC failed" exception.
When this happens, if you just try setting the page property "EnableViewStateMac" to false, it does not solve the problem, it just changes the error message in same navigation behavior:
The state information is invalid for this page and might be corrupted.
This exception appears because Controls using DataKeyNames require Viewstate to be encrypted. When Viewstate is encrypted (Default mode, Auto, is to encrypt if controls require that, otherwise not), Page adds field just before closing of the <form> tag. But this hidden field might not have been rendered to the browser with long-running pages, and if you make a postback before it does, the browser initiates postback without this field (in form post collection). End result is that if this field is omitted on postback, the page doesn't know that Viewstate is encrypted and causes the aforementioned Exception. I.E. page expects to be fully-loaded before you make a postback.
And by the way similar problem is with event validation since __EVENTVALIDATION field is also rendered on the end of the form. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered <form> tag, you'll see something like this: . When a postback occurs, ASP.NET uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception above.
The problem happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.NET cannot validate your click.
Workaround
Set enableEventValidation to false and viewStateEncryptionMode to Never as follows:
<pages enableeventvalidation="false" viewstateencryptionmode="Never">
This has the unwanted side-effect of disabling validation and encryption. On some sites, this may be ok to do, but it isn't a best practice, especially in publicly facing sites.
For more information and other workaround see this blog entry.
This happened to me just a few minutes ago. Luckily, I found this blog post on the subject. The upshot (for me, at least), was that I had two forms, one on the page and one on the control.
I didn't need the one on the page, so I removed it, and the error went away.
I have been struggling with this issue too since lasts few days and finally found the problem.
This error will show up in there are multiple <form> tags are being rendered on a page (be it html <form></form> or Html.BeginForm()).
Check the user controls being rendered, the content page section and also the Master page.
Make sure there is only one form rendered on a page.
This should fix your problem, if the issue persists, check for the for submit buttons rendered on the page (<input type="submit" …/>)
Cheers!
Mayank Srivastava

Resources