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
Related
I am getting validation of view state MAC failing but only very very occasionally.
I am not in a web farm and can't recreate this.
Are there any known factors that can make view state MAC validation fail?
Microsoft blogger Tess Ferrandez has a pretty good post on this:
Viewstate and viewstate validation use a couple of hidden form fields
like __VIEWSTATE and __EVENTVALIDATION. If the page renders so slowly
that the __EVENTVALIDATION field has not rendered by the time someone
clicks the button or control that causes the postback, ASP.NET will
also believe that the viewstate is invalid and report this.
Check whether your viewstate is very large in the problematic page(s). You may want to turn off EnableViewState property on controls that don't need it, especially large databound controls that don't need to remember their state between postbacks.
I am receiving the following error message after an HTTP POST on an ASP.NET form hosted inside a UserControl:
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.
Here's additional info:
I'm running .NET 4.5 RC
It's an Umbraco 4.7-based website
On my local dev machine the form works perfectly
This error only occurs on the staging server which has .NET 4.5 (only), MSSQL 2012 Express, IIS 7.5, Windows 7 (I know, it's not a real server yet, one day maybe...)
The server is not part of a web farm (or garden, tho that should be irrevelant)
The user control does render controls dynamically
I have applied all the latest service packs.
I have run out of ideas now! I have even restarted it and also performed a richual over the server involving a song and a special dance to no avail.
What is important when you are adding controls dynamically is on which event you are adding them.
If you added controls on events that occur after load, they will be part of the viewstate you send to the client.
You will have to add those controls again before LoadViewState is called.
If you run into cases where the decision of which controls to add is itself stored in the ViewState or the value of a control, then remember even before the ViewState is loaded, this data is available in Request.Params
Refer the asp.net page life cycle
I just added EnableViewState="false" to my page placeholder and its gone. Hope it works for u as well.
This Error Mainly Occurs during View state Change: From One Template To other Template like in case of Item Template, Edit Item Template, in Controls like Form View, List Views, Detail View, Grid View in ASP .net (all frameworks);
While Changing from control states say Item Template ---> Edit Template
the followings were going to alter
1) Controls will change (its ID & states)
2) Its Positions will change.
While Transformation of view if any post back occurs you will get Error as
Failed to load viewstate. The control tree into which viewstate is
being loaded....
if you are using separate control for data-binding like (button,link_button_Image_button events) you will get this error reported !
To avoid this error >>> Once state changes from one template to other within method you call data source binding ( Don't call during click or any post backing events ).
OK, so the answer is literally: "Set up a new server with all the same software as the last one and try again" and it works now.
I add "name" attribute with the same value as id, then this problem is gone.
<input type="button" id="extractBomInfoBtn" name="extractBomInfoBtn" value="Extract" class="button textonly" />
I had the same issue. This issue was at client end but it didn't occur in my local system.
After hours of googling, i had written EnableViewState="false" to my table tag in aspx page which has all the dynamic controls and then i removed all the viewstate variables and instead i created some hidden textboxes in the aspx page and accepted DB values into them in code behind and used them throughout my code. It then solved my problem.
But still, i couldn't figure out what was exactly the problem.
In my case I was manipulating the .Text property of a asp:Literal on page load which was causing the issue. In all other cases this never caused me a viewstate error but in this particular case I was changing the .Text value to an html element.
The following caused the error:
<asp:Literal ID="SvgIcon" runat="server" />
SvgIcon.Text = "<svg version=\"1.1\" id=\"Layer_1\" bla bla />"
I was able to resolve the error by adding EnableViewState="false" explicitly to the control:
<asp:Literal ID="SvgIcon" runat="server" EnableViewState="false" />
Check if you have the binding method of the control directly in your page load event. This can cause this problem.
You can add new PlaceHolder per UserControls
OR
You can set enableviewstate=false on the control , if you dont need viewstate
In my case I had a grid view with (OnPageIndexChanging) event
and when I click on a page nothing will happen until I click it twice!
I was refreshing the data source before setting new page index.
This is what I was doing wrong
grd.DataSource = data;
grd.DataBind();
grd.PageIndex = e.NewPageIndex;
This is the right way
grd.PageIndex = e.NewPageIndex;
grd.DataSource = data;
grd.DataBind();
This can happen if you override SaveViewState in your control but don't override LoadViewState.
So I actually ended up discovering that the list of entities I was binding to was not in the same order as the controls in ViewState! I'm still working thru a cleaner solution, but my code is working with ViewStateEnabled = true by having the method which reconstructs my dynamic controls (called from Page_Load) do it differently if !IsPostBack.
Ultimately, I will probably need to fix my sorting algorithm for my nested dynamic controls, but suffice it to say: if you are using the same pattern as I am, of using a List to generate/bind to dynamic controls, and that order is fluid or changing, try comparing Request.Params to find the keys that are relevant to your control hierarchy, and see if they match the order of your List. That solved my issue. Kudos to #nunespascal!
In short, I am dynamically generating all but one tab in an AjaxToolkit tab control, and then populating that with a couple layers deep of placeholders and regular controls (textboxes, dropdownlists, etc), so that's why it's complicated to get the order of everything correct.
Although this is very old question, I had visited this as I got the similar issue. But my issue was generated just because I have added a javascript code in Master page in head tag. That javascript code is reading a value of Session["KeyName"] ,
Code is like below -
$(document).ready(function () {
var allowOpenInNewTab = false;
allowOpenInNewTab = '<%# Convert.ToString(Session["AllowOpenInNewTab"]).ToLower() %>' == 'true';
if (!allowOpenInNewTab && window.sessionStorage.tabId != '1') {
alert("This page is not allowed to be open in another tab, sorry we can not load the page!!");
}
});
When I remove above code then everything was running smoothly but if I keep adding this part of code, it was giving this error of
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate...
Finally I found the solution like if I move my javascript code from head to just before the end of the body tag.
So solution that worked for me was moving javascript code (which is reading Session value from Server tags) to just before end of body tag.
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
Here's the situation: I have a label's text set, immediately followed by a response.redirect() call as follows (this is just an example, but I believe it describes my situation accurately):
aspx:
<asp:Label runat="server" Text="default text" />
Code-behind (code called on an onclick event):
Label.Text = "foo";
Response.Redirect("Default.aspx");
When the page renders, the label says "default text". What do I need to do differently? My understanding was that such changes would be done automatically behind the scenes, but apparently, not in this case. Thanks.
For a little extra background, the code-behind snippet is called inside a method that's invoked upon an onclick event. There is more to it, but I only included that which is of interest to this issue.
A Response.Redirect call will ask the user's browser to load the page specified in the URL you give it. Because this is a new request for your page the page utilises the text which is contained in your markup (as I assume that the label text is being set inside a button handler or similar).
If you remove the Response.Redirect call your page should work as advertised.
After a redirect you will loose any state information associated to your controls. If you simply want the page to refresh, remove the redirect. After the code has finished executing, the page will refresh and any state will be kept.
Behind the scenes, this works because ASP.NET writes the state information to a hidden input field on the page. When you click a button, the form is posted and ASP.NET deciphers the viewstate. Your code runs, modifying the state, and after that the state is again written to the hidden field and the cycle continues, until you change the page without a POST. This can happen when clicking an hyperlink to another page, or via Response.Redirect(), which instructs the browser to follow the specified url.
ASP and ASP.Net are inherently stateless unless state is explicitly specified. Normally between PostBacks information like the value of a label is contained in the viewstate, but if you change pages that viewstate is lost because it is was being stored in a hidden field on the page.
If you want to maintain the value of the label between calls you need to use one of the state mechanisms (e.g. Session, Preferences) or communication systems (Request (GET, POST)).
Additionally you may be looking for Server.Transfer which will change who is processing the page behind the scenes. Response.Redirect is designed to ditch your current context in most cases.
To persist state, use Server.Transfer instead of Response.Redirect.
So, if I may answer my own question (according to the FAQ, that's encouraged), the short answer is, you don't persist view state through redirects. View state is for postbacks, not redirects.
Bonus: Everything you ever wanted to know about View State in ASP.NET, with pictures!
For what it's worth (and hopefully it's worth something), Chapter 6 of Pro ASP.NET 3.5 in C# 2008, Second Edition is a terrific resource on the subject. The whole book has been great so far.
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();"