Failed to load viewstate. The control tree into which viewstate is being loaded - asp.net

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.

Related

Control tree does not match viewstate during the previous request

Im debugging a quite complex system i did not code. On a post back i get this error:
Exception: 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.
Im not very familiar with how the viewstate loads and works. The code builds up some grid view and controls dynamicaly and inserts them into a placeHolder called phCallsDynamicGridHolder
The code that creates the exception is always something similar to this:
HtmlGenericControl summary = createNewCallsSummary(calls);
GridView gv = createGridView(calls, "Calls", width);
phCallsDynamicGridHolder.Controls.Add(summary);
phCallsDynamicGridHolder.Controls.Add(gv);
phCallsDynamicGridHolder.Controls.Add(createNewCallsTotalSummary());
Is anyone familiar with what causes this kind of exception? The page is almost 2000 lines of code, i will past as much as needed upon request.
Psychically debugging, I would guess you are doing that dynamic control creation on every request; you may want to try changing the code so you only do that dynamic control creation within:
if (!IsPostBack)
{
// here
}
Try to disable ViewState for this page.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind=" #####.aspx.cs" Inherits="#####" EnableViewState="false"%>

What are the main differences of defining a control statically or creating it dynamically on page load?

I am working on a project which creates controls dynamically for a form in the page_load event, loads in their current values from the database and saves their values (using FindControl) when the user clicks the continue button.
When I added a control statically in the .aspx page and followed their same procedure of loading the value in the page load and saving it on the button press I found that the value would not save correctly. It seems that it wouldn't save because the click event fires after the page_load, so the page_load of the post back reverted the value and the user entered value was not saved.
The strange thing is that by changing the control to be dynamically created just as all the other controls on the page and keeping the loading and saving the same it now works. Even though the page load still creates the control with the old database value.
It seems like a very fundamental asp .net feature here but i'm just unclear as to what is going on. I suspect it is to do with the timing of creation and maybe when the view state kicks in.
Static page controls are created just like dynamic page controls. The difference might be coming in your Page_Load. Whenever you postback all the controls are created afresh which means they are created with their initial values. This happens because after creating the controls asp.net throws away the controls/objects.
So, when the request comes, the first thing that asp.net does it to recreate the controls by looking at their definitions (in the designer files). On each postback they are created and initialized again losing their state in the process.
But after creating the controls Asp.Net loads any viewstate that is sent along with the request which makes people think that the state is always saved at the server.
What might be happening is that either the viewstate is not enabled for your control (in case they are created in designer), in which case you may try using EnableViewState property to true of the control.
Or, when you're doing a Page_Load, you're forcefully re-initializing everything. And in process losing all the control data. If you could post the logic of Page_Load, it might get clarified.
Make sure that:
you are not setting the value again for the static control in Page_Load. The dynamic control are probably getting around it by grabbing the ViewState and form values at a different stage in the lifecycle.
The dynamic controls are added After the static control. Or at least they are added in a different container. Placement in the control's collection can affect the ViewState, although it doesn't look like your scenario / since what you mention seems to be more about the values in the current post.
The save is happening After the Page_Load in response to the corresponding event.
I've run into similar problems in the past (quite a few times actually), but what helped me the most is understanding the ASP.NET Page Lifecycle.
Microsoft has an article on it which describes it pretty well, but this post by Solomon Shaffer really cleared up everything.
I suggest reading them both and coming back with additional questions regarding to a particular state, when to load/save data etc..
Hope this helps.
Marko
Note that you may want to use Page.IsPostBack property to avoid reinitializing values on button clicks and other events.
private void Page_Load()
{
if (!this.IsPostBack)
{
// Assign values to the controls.
}
}

asp.net 2.0: update formview with jquery

I'm struggling with an issue I just can find a solution for.
First of all, I can't use asp.net AJAX or anything else thant standard asp.net 2.0 as the server admin won't install anything else.
So here is, what I try to do. (For the curious, skip to the bold question below)
My page consists of several parts, each of which gets loaded by jquery.load(url). One of these page parts gets filled with an aspx that contains a form view. As I don't want to have postbacks, I switch to the EditTemplate of the form view by a simple click on a regular html button that submits a parameter indicating the aspx page to switch to edit mode, e.g.
Page_Load(...)
{
if(Request.Params["SwitchEditMode"]) SwitchEditMode();
}
This works perfectly! Now here the part where I'm stuck. The elements in the EditTemplate are based on a select from a database view and bound to the fields by <%# Bind("xx"). Then I have a html button (no asp control) that submits a parameter to the aspx page that tells it to invoke the DataSource update method. In the dataSource_updating method I look for the controls that contain the values I want to save. But these values are always the same, as when I switch to the edit view. No changes I make in the textboxes or dropdowns are preserved.
A long story short, the question how to save the values from EditTemplate back to the database with jquery?
Up to now I tried several approches, that didn't work out.
In the updating() method look for the controls by FindControl and set e.Command.Parameter["xyz"] = foundcontrol.SelectedValue;. The values are always the same as in the beginning.
Set <asp:parameter name="SampleValue" /> and in the EditTemplate <asp:TextBox Value='<%# Bind("SampleValue")#> The values are always null.
Set a hidden input field with the selected value via javascript. This doesn't work as the control within EditTemplate are only visible after the switch into edit mode
So maybe I'm totally wrong with my ideas, heading into a totally wrong direction and this can be accomplished much easier, but up to now I don't know how to achieve this. I could do it without ajax, but for the user experience I'd prefer the version with jquery.
For all that have read this far and not got confused :-), thanks for your effort!
Best regards,
Andreas
I would forget using a form view and just use a regular html form with regular input controls. Return an object from your web service that has all of your values and populate the controls with ajax and then subjmit with ajax. Either do fully asp.net or fully html/jquery with asmx back end. Otherwise it's just too confusing.
If you load both "modes" of the FormView into the same page using AJAX, you're probably getting duplicate field names. One of them contains the unchanged values which are being saved. How will ASP.NET know the difference? You only want to submit the ones from the EditTemplate, which will require a separate form (or some other hack).
Or perhaps your HTML submit button isn't giving ASP.NET what it needs to repopulate the controls. Are you using ViewState in the page with the FormView?
All in all, this sounds like a hairy combination of technologies... as you well know.

What's the difference in behavior between adding a control to an ASPX page directly, loading a control programmatically & adding to a placeholder?

Is there a difference in behavior between adding a control to the ASPX page directly and loading a control programmatically and adding to a placeholder?
The control inherits from System.Web.UI.WebControls.DataBoundControl.
The reason I ask is that I have a control that works when I add it to the ASPX page like so:
...
<blah:GoogleMap ID="GoogleMap1" runat="server" Width="640px" Height="600px" ... DataSourceID="_odsMarkers" DataAddressField="Address" DataTextField="Description">
</blah:GoogleMap>
...
But not when I use the following in a codebehind page:
GoogleMap map = (GoogleMap)this.LoadControl(typeof(GoogleMap), new object[] { });
//... set properties
this.placeholder1.Controls.Add(map); //add to placeholder
Anyone have any ideas why this might be the case?
The control tree ends up the same if you define in markup or add programmatically. However there is plenty of room for the control implementor to screw up along the way.
You can go look how ASP.NET compiles the aspx:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files
The timing when the control is added to the page might be an issue. The usual pattern is add the control in an overload of the CreateChildControls method. If the control needs to resolve viewstate you need to make sure this is called during init, e.g. by calling EnsureChildControls.
Adding to ninja's debbugging hint. Does it make any difference if you add a label the same way. Does it show up?
Is this a user control or server control?
If it's a user control they should be loaded by their path and not their type:
GoogleMap map = (GoogleMap)this.LoadControl("~/Controls/GoogleMap.ascx");
If it's server control then you can just new up an instance:
GoogleMap map = new GoogleMap();
after you have the instance and add it to the control tree (by inserting it into the PlaceHolder) it should perform the same as when it would have been declared in the markup.
If you are setting properties outside of the LoadControl call, why are you making that new empty object array instead of just using the overload that has one parameter?
Also, if you attach a debugger to it and step through, do you notice anything weird about the control before you do your Controls.Add() call? Is there an exception being thrown? if so, which one? if not, what does the markup in the browser look like for where the placeholder is?
"Works" is kind of ambiguous, but if you mean, event handlers are never executed, you need to load it in the page onload event.
If the control requires the use of viewstate you must ensure that it is added to the page BEFORE the Page_Load event, otherwise viewstate will not be populated and most likely events and other items will not function properly.
One important difference is that if you create a control dynamically, you will not get, by default, any values from skins set. You must manually call control.ApplyStyleSheetSkin(page): http://msdn.microsoft.com/en-us/library/system.web.ui.control.applystylesheetskin.aspx

How do I persist the value of a label through a response.redirect?

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.

Resources