Viewstate fails in IE Only - asp.net

I have a page which contains some search fields to query a database, and display results. The viewstate is required to retain the lists of items in dropdowns.
Everything works fine in Firefox (3) & Chrome, but fails in Internet Explorer, but only sometimes (certain actions, such as resetting the form, which really just does a response.redirect with some querystring parameters)... what happens in the Viewstate gets dumped on the URL, and an error page is thrown.
Has anybody come across this before? Perhaps some pointers as to what might be causing this to occur in IE?
Thanks heaps,
greg
UPDATE:
On further investigation, i have determined that the actual error is this:
"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. "
Some more information that might help: This is caused by a user control that is being hosted in a content management system (Umbraco), which might have something to do with why the viewstate is being passed to the page (as the control is contained within a greater page in the CMS). I will investigate this a little further, but any other suggestions would be much appreciated.
cheers
greg
UPDATE 2:
Can anybody suggest why this only happens in IE (and not in FF or Chrome)?? Seems hardly likely its an issue with controls changing or machine keys or other suggestions I've read around the place, if other browsers can deal with it fine.
Any ideas what IE does differently that could cause this failure??
SOLUTION:
Turns out it was a really silly problem - I was using the wrong master template in the CMS, and therefore had 2 form tags. Remove extra form tag, problem solved!
Thanks heaps to bendewey for helping me solve this problem (see the comments in bendewey's post).
That's 4 hours of my life i'd love to get back... but glad i can move on now. Thanks again Stack Overflow community :)

It seems a bit wierd that your viewstate is posting to the the Url. The would happen if you had some custom form tag that was using a GET method instead of the default asp.net page level form tag.
If you need a form tag with the GET method I would set EnableViewState="false" on the Page declaration and setup some sort of list caching. Here is a sample, but you can find much better samples online (specifically ones that do double check locking). This way you can call this every postback and not worry about storing anything in the viewstate.
List<string> getCachedFields()
{
var searchFields = Cache["searchFields"] as List<string>;
if (searchFields == null)
{
searchFields = GetFieldsFromDbOrSomewhereExpensive();
Cache["searchFields"] = searchFields;
}
return searchFields;
}

We've fixed this problem using this blog's suggestion. Please have a look at it ...

I had to remove EnableViewStateMac="false" from the <pages> element to avoid the error in IE.

Related

'Sys' is undefined -- rendered markup is missing a reference to ScriptResource.axd

Yes, the famous "'Sys' is undefined" Microsoft JS issue.
I've already done about 4 hours of digging and trying every suggestion I can find about it, so before you immediately call this a duplicate, here me out please.
Ultimately, this question is exactly the same as this one, but the accepted answer isn't relevant to my situation, and the OP is no longer an active member.
Background
There are about a hundred pages in this application. Each of them ultimately inherits from the same base class. This base class overrides the Init method and dynamically adds a ScriptManager to it as the first Form control.
On one single page out of them all, I encounter the issue described in the post I linked. I mentioned that the accepted answer was relevant. Here's why:
I'm not making any Sys. calls
My page doesn't have any AJAX-enabled controls on it
My page doesn't have any JavaScript on it
My web.config is accurate, it includes the proper handler entries
The issue is reproducible on both IIS 6.0 and IIS 7+
If I explicitly add a ScriptManager to the page via <asp:ScriptManager />, the ScriptResource.axd include still doesn't render to the output page
I've tried clearing browser history, Temporary ASP.NET Files, rebooting, etc. with no change in behavior
An older version of the application in our UAT environment functions correctly; the base page code nor the web.config file have changed since then
I'm completely stumped. It's an ASP.NET 3.5 web site project running on Win Server 2003 with IIS 6.0 (both Prod and UAT). My developer environment is Win7 with IIS 7.5. Same behavior in both environments.
Question
Does anybody have any ideas? I'm starting to think it's a bug in the ASP.NET 3.5.1 framework...
I've just had a similar issue that I seem to have just resolved.
IF you are overriding any other page lifecyle events on your page other than PageLoad make sure to trigger the base version of the event. E.g. I was using OnPreRenderComplete
protected override void OnPreRenderComplete(EventArgs e)
{
base.OnPreRenderComplete(e); //ADDING THIS LINE FIXED THE PROBLEM
//Add THEAD etc to Gridview
if (gvQueue.Rows.Count > 0)
{
gvQueue.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
Since you have tried everything else, and because it is reproducible, I can think of 3 possible causes that you can check:
1) The element not being defined correctly.
Make sure that the head element has runat="server" specified. We always provide an id as well, although I don't think that is strictly required:
<head id="HEAD1" runat="server">
2) The code that is causing the exception is being executed prior to the inclusion of the ScriptResource.axd.
To verify whether this is the case or not, I look at what has loaded in the page so far when the exception occurs. If I don't see the resource that is being reported as missing, I know I have an ordering problem.
I have seen this caused by two hooks of Page.Init (or other methods) in the inheritance tree and when this occurs, you cannot guarantee an order of execution.
3) An invalid page structure.
I have seen numerous cases where a misplaced, easily overlooked character, such as a single quote, double quote or < silently wrecks the page or javascript structure.
To verify that this is not the case, I first validate the page in design mode (Edit, Advanced, Validate Document) and correct any errors.
If there are no errors in design mode, I validate the rendered page by copying the source of the rendered page into an empty page within the project and then validating. This process has caught more than one subtle issue in the page structure.
4) If none of the above solve the problem, there could be an issue with the framework. If there is, it could possibly be caused by element names or order in your page. You can try removing or reordering items in your page until the problem goes away.
Hope this helps.

Failed to load viewstate error after moving website to a new server

I don't really know where to start with this one. I am getting:
`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.`
after moving a website to a new server. The exact same code works on my other server. It happens when I submit one of my forms (but doesn't do it on all form submissions).
Any ideas what can cause this so I have somewhere to look?
Using: ASP.NET 2.
EDIT: I am adding some user controls to a placeholder dynamically at runtime but this same code is working ok on my other server. I have tried clearing the controls in the place holder before adding new ones (as I saw a post about that) but it hasn't helped.
EDIT2: It seems that the postback is just failing. It isn't going into the onClick code of the button either so something is deffintiely screwy .. If I try / catch the exception it seems that all the controls are still added successfully ... Setting my Dynamic UC's to EnableViewState = false resolves this particular error.
EDIT3: Ok, I think I may have a handle on what is happening. For some reason on the old server the form action is default.aspx?action=amend but the new server is showing amend.html?action=amend so I think the re-write module is messing up in IIS. This would explain the control adding issue as well because the action is happening 2 times (I think). I will look into the Rewrite module and see if anything is wrong then post back.
Please, have a look at these articles:
http://blog.typps.com/2008/01/failed-to-load-viewstate-typical.html
http://weblogs.asp.net/guys/archive/2004/12/05/275321.aspx
Or try a simple temporary solution - disable viewstate for this placeholder. Either way, I'm puzzled why it actually works on your first server. I'd be glad if someone else will be able to clarify this subject more.
It turns out that the post back Url for the form is wrong on this server (unsure why at the moment, I will update when I know). This is causing the dynamic controls to be added in an unexpected way and causing the error. I noticed this when I managed to post my form and the content didn't update. I manually adjusted the action url using firebug and all is well.
Worth looking at walther's answer regarding dynamic controls and the viewstate though.
Not sure what caused it but I am manually setting the form action in the page load now and it seems to have solved the issue.

Move ViewState server-side

Okay so I have an ASP.NET application and I'm trying to reduce the overhead for our pages (our users have PCs that average 10 years old).
One of the approaches is to move ViewState server-side. We've plenty of RAM.
I followed the most often cited pattern for doing this here: http://authors.aspalliance.com/robertb/articles.aspx?articleId=2
Because it was written 7 years ago, I had to update some obsolete functions, namely RegisterHiddenField to ScriptManager.RegisterHiddenField and ConfigurationSettings.AppSettings to ConfigurationManager.AppSettings.
This seems to work fairly well, however as soon as I do an AJAX postback, I get the error
Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: The state information is invalid for this page and might be corrupted.
I also noticed that there are now two hidden "__VIEWSTATE" fields on each page with one of them being empty, and one of them having the numeric value from my class. I think this is related to the issue -- perhaps the AJAX update is trying to reading from the empty one instead of the one with the value?
Does anyone know why this error occurs?
The answer is not to use the provided example at all. It's old and outdate, and there is a much better solution provided by the framework itself now.
protected override PageStatePersister PageStatePersister
{
get { return new SessionPageStatePersister(this); }
}
I just added those 4 lines to my BasePage class and voila - instant ~30% page size reduction and it works fine with the AJAX updates.
This is happening because you have not done anything to tell the MS AJAX framework about your new, server-side ViewState mechanism; it is getting the new values, which are simply trimmed-down keys that point to where to find it in the Session object. The AJAX framework knows nothing about that.
Reducing ViewState is most easily done by disabling it on controls where it's not needed at all. If you are using ASP.NET 4.0, you can do even better - disable it by default on the whole page, then only enable it where you need it.
Read this: http://www.hanselman.com/blog/MovingViewStateToTheSessionObjectAndMoreWrongheadedness.aspx
And use Http compression.

Losing the viewstate

I'm storing a few of my properties in the viewstate, so I can use them easily on Ajax requests. My property code looks like this:
public Language Language
{
get { return (Language)ViewState["controls_window_Language"]; }
set { ViewState["controls_window_Language"] = value; }
}
However, my customers have reported some errors, and when I've tracked it down, it's because Language is null. It doesn't happen every time; it appears to be totally random, and I can't reproduce the error. I'm also storing other properties inside the viewstate, and I'm using that property just before Language, so I havn't lost all viewstate.
Most logical reason would be that Language is overwritten, but the only time I write to it is when the page is first loaded.
What can be the reason for losing my viewstate property?
I'm not sure if this is the issue, but using the back/forward navigation in the browser can often cause unexpected results, especially on pages using a lot of asynchronous calls.
Edit: to clarify my thinking...
I'm suggesting this might be why users are seeing the error but you can't reproduce the problem. This is one step in troubleshooting I often forget about...
You say that you write to the viewstate when the page is first loaded.
How do you know that it is the first time the page is loaded, is there a navigation route in your app that could by pass the setting.
As a quick fix, you could try checking if the value is null and then returning a default value.
Try to see if there is a connection between the Session_OnError Event in the global.asax and your ViewState problem
See Dynamically adding controls to ASP.NET - viewstate is not retained after 20 minutes
One possible reason for "losing" ViewState content is Output Cache. I'm facing the same problem and the cause is caching (when I disable it, the problem doesn't occur).

What's a good way to determine what's in my viewstate?

I have a page that has a really huge viewstate (>300KB). ...Yeah, I know. I've narrowed this anomaly down to one user control, but am having trouble determining what exactly that control is putting in there.
I've overridden SavePageStateToPersistenceMedium in the page, but am not great at working with the viewstate object passed in. Could I pass it in to some recursive function that would print out everything that's in the object?
I've tried using freely available viewstate decoders, but none have worked. I always get errors when it attempts to deserialize the viewstate.
I'm pretty much looking for a code snippet here.
Thanks,
Mark
Thanks for the traceing suggestion, esp. the trace.axd thing. But that still only tells me how big the controls are, it doesn't tell me what's in the viewstate. I want to be able to see if there are objects that I'm erroneously serializing to viewstate.
I used to use trace.axd. It lists each request and dumps the contents of the viewstate. You'll have to enable tracing in web.config. If you've got lots of requests you'll want to update the cache size to more than 10.
Fritz Onion's ViewState Decoder is what you need!
I would just add Trace="true" to the page directive on your local machine. The control tree section will show you the viewstate size of each control.
Regarding the issue with viewstate decoders, you might have the viewstate encrypted. Check this post with comments/links on it: http://www.testingreflections.com/node/view/3424.
Update: try turning it off completely on the pages element in the web.config:
<pages ... viewStateEncryptionMode="Never" ... />
View the view state section in this msdn doc How To: Configure MachineKey in ASP.NET 2.0

Resources