Showing posts with label viewstate. Show all posts
Showing posts with label viewstate. Show all posts

Wednesday, March 28, 2012

ViewState

Hi,

Is there any way to turn off ViewState (for real) using the ScriptManager and UpdatePanel? I have EnableViewState on both set to false, but Im still seeing responses of about 100k.

Thanks

Joe

set the enableviewstate=false.

then use ctl+F5 for clear the cached output


Tried that, but it didnt make a difference (unless you are talking about at the page level, in which case I cant without fairly significant changes to things unrelated to what Im working on)

Thanks,
Joe


The EnableViewState property of the ScriptManager only refers to the ViewState of the particular ScriptManager control itself.

Due to the underlying way that UpdatePanels work, the full page's ViewState must be sent to the server. The full page life cycle is still executed in a partial postback, so the ViewState is necessary to re-instantiate the state of the page and it's controls.

However, you canuse page methods to avoid the data-heavy partial postbacks in many cases. The best solution really depends on what exactly you're trying to do, but there's unfortunately no way to remove the ViewState from partial postbacks.

Viewstate - Controls that are there but not there at the same time

Hi All,

I wonder if someone can help. I have just started using ajax and am converting an established application. It uses dynamically created controls to enter parameters for crystal. I have now got a panel that l holds the crystal component, and with testing of directly fed parameters this works fine. As soon as i try and use my dynamic componenets it can't see them. I have gathered this has got something to do with viewstates. I have seen several examples of how to fix this but they are all in C# and the application is in vb. Can anybody step me through this please as i sem to be missing something.

hello,

show me the examples that you found in C# ... i might be able to convert it back to VB for you ... =)


Ttry this online link for converting C# to VB Code...

http://www.kamalpatel.net/ConvertCSharp2VB.aspx


Hi

My conversion is below,

Protected Overrides Function LoadPageStateFromPersistenceMedium()As Object Dim viewStateAs String = Request.Form("__VSTATE")Dim bytesAs Byte() = Convert.FromBase64String(viewState) bytes = Decompress(bytes)Dim formatterAs LosFormatter =New LosFormatterReturn formatter.Deserialize(Convert.ToBase64String(bytes))End Function Protected Overrides Sub SavePageStateToPersistenceMedium(ByVal viewStateAs Object)Dim formatterAs LosFormatter =New LosFormatterDim writerAs StringWriter =New StringWriter() formatter.Serialize(writer, viewState)Dim viewStateStringAs String = writer.ToString()Dim bytesAs Byte() = Convert.FromBase64String(viewStateString) bytes = Compress(bytes) ScriptManager.RegisterHiddenField(Me,"__VSTATE", Convert.ToBase64String(bytes))End Sub
Public Function Compress(ByVal dataAs Byte())As Byte()Dim outputAs MemoryStream =New MemoryStreamDim gzipAs GZipStream =New GZipStream(output, CompressionMode.Compress,True) gzip.Write(data, 0, data.Length) gzip.Close()Return output.ToArray()End Function Public Function Decompress(ByVal dataAs Byte())As Byte()Dim inputAs MemoryStream =New MemoryStream() input.Write(data, 0, data.Length) input.Position = 0Dim gzipAs GZipStream =New GZipStream(input, CompressionMode.Decompress,True)Dim outputAs MemoryStream =New MemoryStream()Dim buffAs Byte()Dim readAs Integer = -1 read = gzip.Read(buff, 0, buff.Length)While (read > 0) output.Write(buff, 0, read) read = gzip.Read(buff, 0, buff.Length)End While gzip.Close()Return output.ToArray()End Function

And the original code was:

protected override object LoadPageStateFromPersistenceMedium()2 {3string viewState = Request.Form["__VSTATE"];4byte[] bytes = Convert.FromBase64String(viewState);5 bytes = Compressor.Decompress(bytes);6 LosFormatter formatter =new LosFormatter();7return formatter.Deserialize(Convert.ToBase64String(bytes));8 }9protected override void SavePageStateToPersistenceMedium(object viewState)10 {11 LosFormatter formatter =new LosFormatter();12 StringWriter writer =new StringWriter();13 formatter.Serialize(writer, viewState);14string viewStateString = writer.ToString();15byte[] bytes = Convert.FromBase64String(viewStateString);16 bytes = Compressor.Compress(bytes);17 ScriptManager.RegisterHiddenField(this.updVS,"__VSTATE", Convert.ToBase64String(bytes));18 }
thanks again

ViewState / PostBacks

Hi all,

Is there any way to update the viewstate actually on the page without having to reload the page?

I know that sounds a bit daft but I would be interested to know - I'm having some issues with my update panels / dynamic controls and this might help.

Hi,

normally the UpdatePanel keeps the viewstate in sync, something a lot of people dislike since that adds significantely to the total data transferred back and forth to the server.

I think your problem is more with the dynamic controls. Be sure to put them in the right eventhandler like Page_Init. Something you can try is to first remove the updatepanel and see if everything works. If it does you can integrate the updatepanel again and recheck.

Grz, Kris.


Hi Kris,

Thank you for your reply.

When you say that the update panel keeps the viewstate in sync, should I notice this on the page if I view source?

For example - lets say to keep things easy when my page loads I view source and there's 100 characters of viewstate, I then perform an action that'll change this, are we saying that the update panel has changed the page so that if I view source now I might see 150 characters for example?

My object that is held in viewstate I can access programmatically, ie, repopulate my object when needed from viewstate and everything is there - I was just wondering whether the actual characters in the view source are going to change or only if there's a full postback?


I doubt you'll see it in a ViewSource; I don't think most browsers reevaluate that after an async postback. You'll want to use the IE Dev toolbar or the Firefox Dom Explorer to get a runtime view of what's in there.


Hi,

another great tool would beFiddler.

Grz, Kris.


Thanks for the info about the additional tools chaps - appreciated.

My problem after further diagnosis seems to be this...

When a user adds a resource, I add the drop down menus using AJAX, the update panel updates, I store the select resource in the view state so that when the update panel updates again I can call back the already selected ones to dynamically rebuild those controls again.

My problem seems to be that when you select an item in the list it doesnt fire the onselectedindexchanged event, I'm completely at a loss why to be honest because I'm using the same function for the controls that are added to the update panel after the user has chosen a resource as I am for the pre-selected resources that come with a role - and thats working?

Any thoughts? I've attached a screenshot so you can perhaps get a better idea of what I'm trying to achieve...

Application Screen Shot


Well, I'm not sure how to solve the problem offhand; I tend to limit my use of updatepanels where possible. I'm not entirely sure at what point you're adding your controls based on your description; are you adding them using javascript on the client? That's what it sounds like. if that's the case, then you're not going to be able to do what you're trying to do b/c they don't exist on the server. If you're adding them on the server during the updatepanel's firing, then I'm pretty sure the upd won't recognize them (iirc, it loads all its triggers, etc, on the initial load during Init or PreInit of the page). You might be able to manually force an update by using the PageRequestManager.update() function on the client, and then wire the dropdown's event handler to a function that calls that; but I'm just guessing at this point.


Hi Paul, thank you for your reply...

To clarify what I'm trying to do then...

Looking at the screenshot above you'll notice two clear sections "Pre-selected resources" and "Additional resources".

My code gets the data for the role from SQL, and builds the 3 sets of drops downs (for access level and further detail) adding them to a table control.

I have them also in independent updatePanels, ie, one around each set of drop downs, when the user selects and access level in the first drop down menu (on the left) it'll run my code server side to update the items in the second drop down menu (on the right).

So in the screenshot, the top half of the page is working as expected, and also includes validators etc if nothing is selected on either of the menu's (left or right).

The "additional resources" is where it got more difficult...

When the user clicks on the "Add Resource Hyperlink" a popup window is launched which displays a list of all available resources as hyperlinks, each of the hyperlinks has a javascript call wired up so that when they are clicked it will place the ID of the resource into a hidden text box on the parent window. It also "clicks" a hidden button on the parent window.

My code then detects the click even and grabs the resource id from the hidden text field. I use this to then go and get all of the access levels for the resource and add a set of drop down menus to the "additional resources" part of the page, this has its own containing updatePanel.

The set of drop down menus are added with their own updatePanel as per the "pre-selected resources" section, the code to generate these is a generic function used by both.

I am then expecting the onSelectedIndexChanged event on the access level drop down (on the left) to fire when the user selects an item which in turn should then run my code to populate the further detail drop down menu (on the right) - this is what is currently not working - there are no errors, server or client side - simply nothing happens.

Initially I had a problem where I was adding the resource (with the drop downs) to the update panel and when I added the next one the first disappeared, this turned out to be because the server did not know anything about them as they were added client side, I got around this by changing my onSelectedIndexChanged code to add the selected resource to my userRegistration object held in viewstate, and then each time it updates the update panel it rebuilds the controls, thus any previously selected ones appear.

I hope this helps to clarify what I'm trying to do and where it isn't working, if it helps I'm happy to take a few more screenshots for each of the steps of the process to help further...


Any chance I can see the code related to those additional drop downs? PM is fine if you're not comfortable posting it here.

Also, use Fiddler to see if the event fires, but is not handled by the server, or it doesn't fire at all.

If it's fired, but not handled by the server, then you might have to do some manual inspection of the request to see if one of those dynamic controls fired it and then manually call the handler. If it's not fired, then you might have to do some .js hotness to get the controls properly wired up.

Paul


Hi Paul,

Thanks for your reply - no problem posting the code up - no need to PM - hadn't done it thus far as there's quite a bit of it...anyway...here goes...this should be most of the relavent stuff I think - if there's anything else let me know - last night I got as far as when you change the selected item in the access level (left hand drop down) nothing happens, but then on the second time you change the selection it fires something - not sure what as it then didn't display any controls - lol...looks like something might be nearly working...maybe...

Private Sub PopulateRoleBasedResources()' declare variablesDim userRegistrationAs UserRegistrationDim roleResourceCollectionAs RoleResourceCollection.SerializableRoleResourceCollectionDim roleResourceAs RoleResource.SerializableRoleResourceDim addSpacerAs Boolean' instantiate userRegistration =New UserRegistration(ViewState) roleResourceCollection =New RoleResourceCollection.SerializableRoleResourceCollection(userRegistration.RoleID)' iterateFor Each roleResourceIn roleResourceCollection' populate _iteration += 1' check position in collectionIf roleResourceCollection.AtEndOfCollection =True Then' populate addSpacer =False Else' populate addSpacer =True End If' create table rows for resource access levels and parameter options CreateTableRowsForResourceAccessLevelAndParameterOptions(AccessLevelParameterOptionsType.PreSelected, tblRegistrationPreSelectedResources, _iteration, roleResource, roleResource.AccessLevels, addSpacer)Next End Sub Protected Sub ddlResourceAccessLevelSelectedIndexChanged(ByVal senderAs Object,ByVal eAs System.EventArgs)Dim dropDownListAs DropDownListDim resourceAccessLevelIDAs GuidDim controlIterationAs String Dim requiredFieldValidatorAs RequiredFieldValidator' populate controlIteration ="" dropDownList = sender resourceAccessLevelID =New Guid(dropDownList.SelectedItem.Value.ToString())Select Case sender.id.ToString.Contains("AccessLevel")Case True controlIteration = Right(sender.ID.ToString, (Len(sender.ID.ToString) - 23))Case False controlIteration = Right(sender.ID.ToString, (Len(sender.ID.ToString) - 21))End Select' find our resourceParameter drop down list dropDownList = Page.FindControl("ddlResourceParameter_" & controlIteration)' populate PopulateResourceParameters(resourceAccessLevelID, dropDownList)' find our resourceAccessLevel requiredFieldValidator requiredFieldValidator = Page.FindControl("vldResourceAccessLevel_" & controlIteration)' validate requiredFieldValidator.Validate()End Sub Private Sub PopulateResourceParameters(ByVal resourceAccessLevelIDAs Guid,ByRef dropDownListAs DropDownList)' declare variablesDim sqlAs SQLDim resourceParametersAs Data.DataTableDim listItemAs ListItem' check resourceAccessLevelIDIf resourceAccessLevelID.ToString <>"00000000-0000-0000-0000-000000000000"Then' instantiate sql =New SQL' populate resourceParameters = sql.GetResourceAccessLevelParameters(resourceAccessLevelID)' check we returned some resourceParametersIf resourceParameters.Rows.Count > 0Then' populate dropDownList.DataSource = resourceParameters dropDownList.DataTextField = resourceParameters.Columns("ResourceParameterName").ColumnName.ToString() dropDownList.DataValueField = resourceParameters.Columns("ResourceParameterID").ColumnName.ToString() dropDownList.DataBind()' instantiate listItem = CreateListItem("00000000-0000-0000-0000-000000000000","Please Select") listItem.Selected =True' add list item to drop down list dropDownList.Items.Insert(0, listItem)Else' instantiate listItem = CreateListItem("00000000-0000-0000-0000-000000000000","None Available") listItem.Selected =True' add list item to drop down list dropDownList.Items.Add(listItem)' TODO: Send error to webmaster if no rolegroups have been loadedEnd If' housekeeping ' Dispose(sql)Else' clear all previously added resourceParameters dropDownList.Items.Clear()End If End Sub Protected Sub ddlResourceParameterSelectedIndexChanged(ByVal senderAs Object,ByVal eAs System.EventArgs)' declare variableDim controlIterationAs Integer Dim requiredFieldValidatorAs RequiredFieldValidator' populate controlIteration = Right(sender.ID.ToString, (Len(sender.ID.ToString) - 21))' find our resourceAccessLevel requiredFieldValidator requiredFieldValidator = Page.FindControl("vldResourceParameter_" & controlIteration)' validate requiredFieldValidator.Validate()End Sub Private Sub CreateTableRowsForResourceAccessLevelAndParameterOptions(ByVal accessLevelParameterOptionsTypeAs AccessLevelParameterOptionsType,ByRef tableAs Table,ByVal iterationAs Integer,ByRef enumeratorAs Object,ByRef enumerableObjectAs Object,ByVal addSpacerRowAs Boolean)' declare variablesDim tableRowAs TableRowDim tableCellAs TableCellDim dropDownListAs DropDownListDim listItemAs ListItemDim updatePanelAs UpdatePanelDim requiredFieldValidatorAs RequiredFieldValidatorDim requiredFieldValidator2As RequiredFieldValidatorDim accessLevelDropDownListIDAs String Dim parameterDropDownListIDAs String Dim accessLevelValidatorIDAs String Dim parameterValidatorIDAs String Dim resourceAccessLevelAs ResourceAccessLevel.SerializableResourceAccessLevel' populate resourceAccessLevel =Nothing accessLevelDropDownListID ="ddlResourceAccessLevel_" & iteration accessLevelValidatorID ="vldResourceAccessLevel_" & iteration parameterDropDownListID ="ddlResourceParameter_" & iteration parameterValidatorID ="vldResourceParameter_" & iteration' *** First table row *** ' *** First table cell *** ' instantiate tableRow = CreateTableRow() tableCell = CreateTableCell(40, HorizontalAlign.Left)' populate AddWebControlToControlCollection(tableCell, CreateImage(16, 1,"UI/Images/Misc/Shim.gif","","")) AddWebControlToControlCollection(tableCell, CreateImage(16, 16,"UI/Images/Misc/BulletPoint.gif","Bullet Point","*")) AddWebControlToControlCollection(tableCell, CreateImage(5, 1,"UI/Images/Misc/Shim.gif","",""))' add tablecell to tablerow tableRow.Cells.Add(tableCell)' *** First table row *** ' *** Second table cell *** ' instantiate tableCell = CreateTableCell(HorizontalAlign.Left)' populate tableCell.Text = enumerator.Name tableCell.Style.Add("font-weight","bold")' add tablecell to tablerow tableRow.Cells.Add(tableCell)' *** First table row *** ' *** Third table cell *** ' instantiate tableCell = CreateTableCell(HorizontalAlign.Left)' populate tableCell.Text =" "' add tablecell to tablerow tableRow.Cells.Add(tableCell)' *** First table row *** ' *** Fourth table cell *** ' instantiate tableCell = CreateTableCell(HorizontalAlign.Left)' populate tableCell.Text =" "' add tablecell to tablerow tableRow.Cells.Add(tableCell)' add tablerow to table table.Rows.Add(tableRow) tableRow =Nothing tableCell =Nothing' *** Second table row *** ' *** First table cell *** ' instantiate tableRow = CreateTableRow() tableCell = CreateTableCell(40, HorizontalAlign.Left)' populate tableCell.Text =" "' add tablecell to tablerow tableRow.Cells.Add(tableCell)' *** Second table row *** ' *** Second table cell *** ' instantiate tableCell = CreateTableCell(HorizontalAlign.Left) updatePanel =New UpdatePanel dropDownList =New DropDownList listItem =New ListItem("Please Select","00000000-0000-0000-0000-000000000000") listItem.Selected =True' populate updatePanel.ID ="upnAccessLevelParameter_" & iteration.ToString updatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional updatePanel.RenderMode = UpdatePanelRenderMode.Inline dropDownList.AutoPostBack =True dropDownList.ID = accessLevelDropDownListID dropDownList.CssClass ="vam" listItem.Selected =True' create event handler ' AddHandler dropDownList.SelectedIndexChanged, AddressOf ddlPreSelectedResourceAccessLevelSelectedIndexChangedAddHandler dropDownList.SelectedIndexChanged,AddressOf ddlResourceAccessLevelSelectedIndexChanged' add listitem to dropdownlist dropDownList.Items.Add(listItem)'iterateFor Each resourceAccessLevelIn enumerableObject' instantiate listItem =New ListItem(resourceAccessLevel.Name, resourceAccessLevel.ID.ToString)' add listitem to dropdownlist dropDownList.Items.Add(listItem)Next' instantiate requiredFieldValidator = CreateRequiredFieldValidator(dropDownList.ID.ToString, accessLevelValidatorID,"00000000-0000-0000-0000-000000000000","<img class=""vam"" src="http://pics.10026.com/?src="UI/Images/Icons/Warning.gif"" style=""width:16px;height:16px;"" title=""Required information missing"" alt=""!"" />","Required information","UserRegistrationFurtherDetailStep3")' populate updatePanel.ContentTemplateContainer.Controls.Add(dropDownList) updatePanel.ContentTemplateContainer.Controls.Add(CreateImage(16, 16,"UI/Images/Misc/MandatoryField.gif","Required information","Required information","vam", 0, 0)) updatePanel.ContentTemplateContainer.Controls.Add(requiredFieldValidator) updatePanel.ContentTemplateContainer.Controls.Add(CreateImage(16, 16,"UI/Images/Icons/Information.gif","Click to view Access Level information","Information","vam", 5, 35))' instantiate dropDownList =New DropDownList' populate dropDownList.AutoPostBack =True dropDownList.ID = parameterDropDownListID dropDownList.CssClass ="vam"' create event handlerAddHandler dropDownList.SelectedIndexChanged,AddressOf ddlResourceParameterSelectedIndexChanged' instantiate requiredFieldValidator2 = CreateRequiredFieldValidator(dropDownList.ID.ToString, parameterValidatorID,"00000000-0000-0000-0000-000000000000","<img class=""vam"" src="http://pics.10026.com/?src="UI/Images/Icons/Warning.gif"" style=""width:16px;height:16px;"" title=""Required information missing"" alt=""!"" />","Required information","UserRegistrationFurtherDetailStep3") requiredFieldValidator2.IsValid =True' populate updatePanel.ContentTemplateContainer.Controls.Add(dropDownList) updatePanel.ContentTemplateContainer.Controls.Add(CreateImage(16, 16,"UI/Images/Misc/MandatoryField.gif","Required information","Required information","vam", 0, 0)) updatePanel.ContentTemplateContainer.Controls.Add(requiredFieldValidator2)' populate AddWebControlToControlCollection(tableCell, updatePanel)' add tablcell to tablerow tableRow.Cells.Add(tableCell)' *** Second table row *** ' *** Third table cell *** ' instantiate tableCell = CreateTableCell(HorizontalAlign.NotSet)' populate tableCell.Controls.Add(CreateImage(16, 16,"UI/Images/Icons/Information.gif","Click to view Further Detail information","Information","vam", 5, 5))' add tablecell to tablerow tableRow.Cells.Add(tableCell)' instantiate tableCell = CreateTableCell(HorizontalAlign.Left)' *** Second table row *** ' *** Fourth table cell *** ' populate tableCell.Text ="Empty cell"' add tablecell to tablerow tableRow.Cells.Add(tableCell)' add tablerow to table table.Rows.Add(tableRow)' add a spacer if requiredIf addSpacerRow =True Then' instantiate tableRow = CreateTableRow() tableCell = CreateTableCell(2, HorizontalAlign.Left)' populate tableCell.Text =" "' add tablecell to tablerow tableRow.Cells.Add(tableCell)' add tablerow to table table.Rows.Add(tableRow)End If End Sub

Ok - I've had some success!!

I ran it through in debug mode with a break point on the page load, this is where I have a test to see if we're posting back asynchronously and build the page depending on some factors.

What I noticed was that when I call my onSelectedIndexChanged event handler function I add the resource to the userRegistration object and then rebuild the controls on the page (iterating through those in my object) - but when I do any other form of postback (even if asynchronously) I wasn't calling this - and this was why they seemed to disappear.

So, I've amended the code to incorporate this and now I have the controls not disappearing, I've even managed to get them to fire and populate the further detail drop down menu (on the right) - the only minor thing to resolve now is where this is call from - as if I leave the code in the onSelectedIndexChanged event handler function then my controls get duplicated on the page, if I take it out then all but the most recently added one appear but I'm hoping this will be easy to resolve - get there though - and even my validators work - lol - gotta love OO!Big Smile


Glad I could help. seems like you'd want to pull the code in your onSelectedIndexChanged handler out into a helper function, and then have the OSIC handler perform inspection of the sender to determine whether to fire that version, or a different version that doesn't create duplicates. Alternatively, if you keep (as you suggested) your created 'stuff' in the state bag, then you should just be able to inspect the contents of the state bag to see what's there, and then add to it as needed, rather than blindly adding, if that make ssense.


Hi Paul,

Ok - I'm still struggling a bit with this...

The controls are being added which is a good thing - however, if I add one control, I can then use it and the OSIC event fires - great...

If I add more than one control then you seem to need to select 2 different values before it fires...I've followed this through in the debugger and I have a theory - but thats about it!

At the moment I've got the code that iterates through the resources in the userRegistration object as a separate sub, I call this when the page loads (based on certain criteria), so that all of the items are displayed, part of this process is to clear the table first, thus anything thats there is cleared, then all of the resources are rendered.

When the user adds a new one I call this sub again, as obviously I need to show the one they just added...

It looks as if the building of the controls twice might be causing the problem, whilst they have ID's that are set by me I get the feeling that its losing some reference from what had the OSIC event on the first fire, ie, nothing happens, then the page is rebuilt and the second time it seems to work - its very strange...

I'm not sure of the best approach now - I need to display whatever resources have already been added AND the one that has just been added and obviously have all of them firing correctly...

Any thoughts?


Hi Rob; got your PM; sorry I didn't respond earlier.

I'm not really sure based on your code what might be causing the problem; can you look at the rendered' page's source through a runtime tool like the IE developer toolbar and check the DOM tree and the attributes of each of your ddls to see what they look like at each step of the operation? If you have the site somewhere that's accessible, I'll look at it that way for you.

I'm also not entirely clear on the behavior you're describing. Let me repeat my undertanding and you can tell me where I'm mistaken: What you're experiencing is that when you have one dynamic dropdown on the page all is well. That is a ddl that is added after the initial page load. When you later add a second dynamic control, the first time you make a selection on it, nothing happens. the second time you make a selection on it, you get the expected behavior. Is that correct?


Hi Paul,

No worries, I just thought I'd give you a try on this as you helped me out last timeSmile

I dont have the developer tool bar installed, so I'll get it and install it, I've never used it before so I hope its intuitive - you've seen what I mess I can get into! hehe...

I think your description of your understanding was correct - albeit that obviously each time I try to fix this I change something and then that changes the outcome, but I typically then put it back to how it was and go around in circles...

I can confirm that if you only add ONE additional resource it seems to work perfectly, but I suspect that this is because the method to build the controls is being called twice, once in the page load, and once on the button click event, well actually 3 times then - the page loads, it tries to iterate through the collection of already selected resources but there aren't any, so its doesnt, then you select one, the javascript clicks the button, the ajax enables the .net method to be called which adds a resource object to my collection in the userRegistration object in viewstate, and then calls the method to build the controls. No doubt at some point here there's been a postback either full or async - async most likely, thus the same call to build the controls would have happened there too - thus I believe its called twice...maybe thats why if you only add one it works..

I have a line of code in the build mehtod which clears all rows from the current table, this was added to ensure that I didn't get duplicates on the page, if I remove this then I do get duplicates so felt it best to keep this in, so each time it will remove everything from the table, and then rebuild.

If I remove the call to build from the add resource method (fired from the button click) then I never see the most recently added object on the page, my code has added it to the viewstate though so on the next postback/async postback the build method is called and they all appear.

Regarding the number of times you have to select something in the drop downs my theory is that when its say the second control, its run the build method AFTER the page_init, .net doesn't know about the control althought it was added programmatically and is on the page - and thus I believe (probably wrong) it equally doesn't know about the eventhandler (made programmatically with addHandler) - therefore when I select an option it doesnt fire my event, instead it does the autopostback because this is set to true to try and enable the AJAX etc...as such when the postback is called it runs my build method which then takes the resources from the collection in my userRegistration object from viewstate and builds the controls - I think (although have almost lost the plot now) - at this stage the selected index change event DOES work because .net now knows about the controls...and as such the second drop down menu is populated...

I think thats about it...

ViewState and Atlas

Hi

I encountered a problem involving viewstate and PageMethods (web methods in an aspx page).

I was submitting some control values, only one control on the page is designed as a <asp:listbox />, the rest of the controls are generic HTML. While Atlas.js constructed the proxy to the PageMethod and the arguments (Web.Net.PageMethodRequest) the Atlas.js javascript does some sort of check on the page controls, in which viewstate is a hidden input, adding it to a dictionary (refer line 3495 in Atlas.js)

Some sort of exception is generated but no information is available to determine the source. The code behind to the PageMethod didn't get hit in debug mode and it wasn't until I inspected the request/response in Fiddler that I came across a message indicating a corrupted viewstate.

After disabling viewstate on the <asp:listbox> the request got through to my [WebMethod] in the code-behind.

There is a problem with PageMethods and viewstate, or have I missed something.

Craig

An update for those who might be encountering the same problem with altas (Jan-06 CTP) and ViewState.

As mentioned in my previous post, in the file Atlas.js on line 3495, a procedure adds to the variable bodyDictionary all 'submittable' HTML element e.g <input /> this includes <input type="hidden" /> which means that<inputid="__VIEWSTATE" /> is added to the bodyDictionary variable.

Next in the procedure, is a call Web.Net.WebRequest.createQueryString(bodyDictionary, ...);

This is where IMHO the viewstate corruption is occuring between the client service calls to the server. In my case, I make a call to a [WebMethod] which is contained in an aspx page. So my client function is something like this:

functionfoo() {
PageMethod.GetFoo('hello');
}

My aspx.cs [WebMethod] is like the following:

[WebMethod]
public string GetFoo(string text) {
return text+=" get foo";
}

My page wrapes a user control in an<atlas:UpdatePanel>the user control contains an<asp:Repeater>control.

Has anyone experienced this, or am I the lucky one? To avoid the error 500, I removed the check for HTML elements with a type of hidden. But I'm not sure if this is a good thing...

Craig

PS: I can post the stack trace for those who might be interested.


Further, using PageMethod seems to faciliate the viewstate corruption. for kicks I moved the [WebMethod] from the aspx page into an ASMX file, reversed my Atlas.js script hack and the viewstate problem has gone. I hope the PageManager is a little more robust in the rtm.


Hi,

I'm not able to reproduce the behavior that you described. Could you post the stack trace and also the relevant page code?

Hi Garbin

Stack Trace
[FormatException: Invalid length for a Base-64 char array.]
System.Convert.FromBase64String(String s) +0
System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +72
System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4
System.Web.UI.ClientScriptManager.EnsureEventValidationFieldLoaded() +172

[ViewStateException: Invalid viewstate.
Client IP: 127.0.0.1
Port: 3520
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)
ViewState: /wEWCAKbhpuAAgLEtM6pBgLN/7aVCAKe4MuSDQLL7+H/CgLL7 3/CgKs5ZucDgLNoqBMLo1Lj5/N S5y dQM87L I5JMzQ=
Referer:http://localhost/Unsd/COC/ExchangeRateView.aspx?countryCode=36
Path: /Unsd/COC/ExchangeRateView.aspx]

[HttpException (0x80004005): The state information is invalid for this page and might be corrupted.]
System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +116
System.Web.UI.ClientScriptManager.EnsureEventValidationFieldLoaded() +209
System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +67
System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +106
System.Web.UI.WebControls.TextBox.LoadPostData(String postDataKey, NameValueCollection postCollection) +31
System.Web.UI.WebControls.TextBox.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +11
System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +408
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6953
System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +154
System.Web.UI.Page.ProcessRequest() +86
System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +18
System.Web.UI.Page.ProcessRequest(HttpContext context) +49
ASP.exchangerateview_aspx.ProcessRequest(HttpContext context) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\unsd_coc\bdef81f1\ee1d3cb5\App_Web_ytigk7vl.8.cs:0
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +154
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +64

Page Code (aspx.cs)
[WebMethod]
publicExchangeRate GetExchangeRate(int countryCode,int year) {
returnCountryManager.Instance.GetExchangeRate(countryCode,
newint[] { year });
}

Page Code (aspx - javascript)
function GetExchangeRate(countryCode, year) {
// Call the server.
PageMethods.GetExchangeRate(countryCode, year, RequestCallback);
}

function RequestCallback(exchangeRate) {
// Bind the result to the controls.
document.getElementById("ctl00_contentPlaceholder_textboxYear").value = exchangeRate.Year;
document.getElementById("ctl00_contentPlaceholder_textboxIMF").value = exchangeRate.IMF;
document.getElementById("ctl00_contentPlaceholder_textboxUNOP").value = exchangeRate.UNOP;
document.getElementById("ctl00_contentPlaceholder_textboxOther1").value = exchangeRate.Other1;
document.getElementById("ctl00_contentPlaceholder_textboxOther2").value = exchangeRate.Other2;
document.getElementById("ctl00_contentPlaceholder_textboxNote").value = exchangeRate.Note;
}

Page Code (aspx - html)
<!-- Exchange Rate Control -->
<atlas:UpdatePanelID="updatePanelExRate"runat="server"Mode="Conditional">
<ContentTemplate>
<unsd:ExchangeRateControlid="exchangeRateControl"runat="server"/>
</ContentTemplate>
<Triggers>
<atlas:ControlEventTriggerControlID="buttonSave"EventName="Click"/>
</Triggers>
</atlas:UpdatePanel>

The ExchangeRate control is populated in the Page_Load event of the aspx Page by passing an array to a property accessor in the control, the array provides is the data source to a repeater. The ItemTemplate in the repeater contains a link to invoke the GetExchangeRate javascript in the page (above).

Hope this helps.

Craig


I don't know if its the same issue or not, but viewstate corruption is rampant in the QuickStart tutorials... There were several times where I ran 3 or 4 different "run this" tutorials in a row only to have the viewstate corruption error message appear on me. Sometimes it was fixed with a refresh of the page, sometimes it never went away.
hi Guys...
even i got the same problem when i put my [webmethod] in code behind.i tried removing type=hidden from atlas.js line 3495 and it is working.please let me know for the solution as we just can not remove any thing from coreatlas files even though doing the same results in expected output.

thanks
Jaideep

I tried a few things, but was not able to repro. Could you give this a try with the March CTP to see if it still happens?

thanks,
David


I have a similar problem with teh session state.

I have narrowed it down to a web user control that raises an event.

The code behind that implements the event sets the session var and then does a redirects.

on the redirect page the session state is blown away. cant figure out why

steps to reproduce

- create a web user control (define an event and raise it)

- create a page and place the wuc on it (trap for the wuc event and set a session var and do a redirect to 2nd page

- in 2nd page Page_load check the session state

ViewState and JavaScript

Hi, I posted this in another forum, and I am hopping I'll get more response here.

I have two list boxes that I use for dual list box functionality, and there are four buttons that allow movement of the items from one box to another. All this is performed using javascript functions attached to buttons those 4 buttons. There is one more button that is supposed to get values from the right box and print reports. All controls are in update panel. In Pre-Reneder method I am checking to see if there are any items in the right box, and there aren't ever any. Is there something that I need to do so state of the controls would be maintained?

Here is the javascript

function MoveDualList( srcListId, destListId, moveAll )

{

var srcList = document.getElementById(srcListId);

var destList = document.getElementById(destListId);

// Do nothing if nothing is selected

if ( ( srcList.selectedIndex == -1 ) && ( moveAll ==false ) )

{

return;

}

newDestList =new Array( destList.options.length );

var len = 0;

for( len = 0; len < destList.options.length; len++ )

{

if ( destList.options[ len ] !=null )

{

newDestList[ len ] =new Option( destList.options[ len ].text, destList.options[ len ].value, destList.options[ len ].defaultSelected, destList.options[ len ].selected );

}

}

for(var i = 0; i < srcList.options.length; i++ )

{

if ( srcList.options[i] !=null && ( srcList.options[i].selected ==true || moveAll ) )

{

// Statements to perform if option is selected

// Incorporate into new list

newDestList[ len ] =new Option( srcList.options[i].text, srcList.options[i].value, srcList.options[i].defaultSelected, srcList.options[i].selected );

len++;

}

}

// Populate the destination with the items from the new array

for (var j = 0; j < newDestList.length; j++ )

{

if ( newDestList[ j ] !=null )

{

destList.options[ j ] = newDestList[ j ];

}

}

// Erase source list selected elements

for(var i = srcList.options.length - 1; i >= 0; i-- )

{

if ( srcList.options[i] !=null && ( srcList.options[i].selected ==true || moveAll ) )

{

// Erase Source

srcList.options[i] =null;

}

}

//sort destinantion list box

SortListBox(destList,compareText)

}// End of moveDualList()

function compareText (opt1, opt2)

{

return opt1.text.toLowerCase() < opt2.text.toLowerCase() ? -1 :

opt1.text.toLowerCase() > opt2.text.toLowerCase() ? 1 : 0;

}

function SortListBox (pListBox, compareFunction)

{

if (!compareFunction)

{

compareFunction = compareText;

}

var options =new Array (pListBox.options.length);for (var i = 0; i < options.length; i++)

{

options[i] =new Option ( pListBox.options[i].text,

pListBox.options[i].value,

pListBox.options[i].defaultSelected,

pListBox.options[i].selected );

}

options.sort(compareFunction);

pListBox.options.length = 0;

for (var i = 0; i < options.length; i++)

{

pListBox.options[i] = options[i];

}

}

Hi,

ListBoxes do not post their values when HTML form is submitted. ListBoxes do only post their selected values. Therefore, any items added to the list box on the client are not available on the server. Your page restores list boxes from the viewstate encoded in the hidden field at the server and it doe not know anything about changes made to your listboxes on the lcient.

As a simple solution, I can suggest you placing a hidden field for your list box on the client and every time you change list box on the client, place a comma separated list of value into that hidden field. Then at the server, you can retrieve coma seperated list of values and populate your list (if you still need to render the same page) or process items.

-yuriy
http://couldbedone.blogspot.com

ViewState and JavaScript

Hi guys,

I have two list boxes that I use for dual list box functionality, and there are four buttons that allow movement of the items from one box to another. All this is performed using javascript functions attached to buttons those 4 buttons. There is one more button that is supposed to get values from the right box and print reports. All controls are in update panel. In Pre-Reneder method I am checking to see if there are any items in the right box, and there aren't ever any. Is there something that I need to do so state of the controls would be maintained?

Are you adding the Right side listbox items in client side by JS/DHTML? If so the viewstate will not sync with the server.


Yes I am using javascript/dhtml. So is there other way to do it on client side that will sync up with server?


Hi

I'm afraid there is no way to do this.Please change it to using AJAX to do that at server side.

Good luck.


Hi,

Please refer to this article[ http://aspalliance.com/1071_Smart_ListControl_in_ASPNET_1x20 ], it explains the reason and gives a solution.

Hope this helps.

ViewState in Session is still uploaded after AsyncPostBack

Hi all,

Here is the basic setup of my page.

- ViewState stored in session
- AutoCompleteExtender using a WebService
- UpdatePanel triggered by button next to AutoComplete TextBox

Here is the behavior I'm experiencing (note that I have validated this with Fiddler):

Page loads first time. "id="__VIEWSTATE" value="y0V/cubnEZ1qzAvIgW0oRpVSc8AvJU6rtssTVFt7+B8="
ViewState is short as expected because storing it in the session.

Now, I click on the button to activate the UpdatePanel, causing a partial postback. This takes much longer than expected. After inspecting with Fiddler I see that it is uploading 50K. I inspect the Request and notice that most of it is my ViewState (I have a repeater on the page). I even turned EnableViewState off on the Repeater and it still uploads it.

My questions are:

1. Where is this uploaded ViewState coming from? It was not downloaded, is it generated clientside by JavaScript?
2. How can I stop this ViewState from being uploaded?

Regards,
Cole

I now realize this is not the viewstate but all of the form elements names & values being concatenated together. Is there a way to adjust what gets sent back from the controls on a AsyncPostBack?


The only way I'm aware of is to not use updatepanels to traffic your info, but instead to use web services, page methods, or hand-jam your own webrequest.

ViewState Management Problem

hi

every one using ajax knows that viewstate problem exists in it.....

is there any remedy available for that problem???

Could you please be more specific about what problems you're refering to?

Thanks,

Eilon

ViewState of CollapsiblePanelExtender

I have several collapsible panels on a web form, and I cant seem to get them to remember their viewstate. Am I missing something or is this not possible?

Here is an example:

<asp:Content ID="Content2" ContentPlaceHolderID="DetailContentPage" Runat="Server"><div style="margin-left:10px"> <asp:Panel Width=100% ID="mainPanel" runat=server > <table width=100% align="left" cellspacing=0 cellpadding=10 > <tr> <td> <asp:Panel ID="ResHeaderPanel" runat="server" CssClass="formPanelHeader" Height="32px"> <div style="padding:5px; cursor: pointer;" > <div style="float:left; margin-top:4px;"> <asp:Image ID="imgResArrow" runat="server" ImageUrl="~/images/expand.jpg"/> </div> <div style="float:left; margin-left:6px; vertical-align:middle;">Engine Settings</div> <div style="float:left; margin-left:30px; margin-top:4px; font-size:x-small" > <asp:Label ID="lblResHeaderHint" runat="server">(Show Details...)</asp:Label> </div> </div> </asp:Panel> <asp:Panel ID="ResPanel" runat="server" CssClass="formPanel"> <table> <tr> <td width=200px>Number of Rooms:</td> <td width=70%><asp:TextBox ID="txtNumRooms" runat="server" MaxLength=200 width=70% /></td> </tr> <tr> <td>Time Zone: </td> <td><asp:TextBox ID="txtTimeZone" runat=server MaxLength=200 width=70%/></td> </tr> <tr> <td>form controls removed </td> <td></td> </tr> <tr> </table> </asp:Panel><!-- ******************************** --> <asp:Panel ID="ContactheaderPanel" runat="server" CssClass="formPanelHeader" Height="32px"> <div style="padding:5px; cursor: pointer;" > <div style="float:left; margin-top:4px;"> <asp:Image ID="Image1" runat="server" ImageUrl="~/images/expand.jpg"/> </div> <div style="float:left; margin-left:6px; vertical-align:middle;">Contact Details</div> <div style="float:left; margin-left:30px; margin-top:4px; font-size:x-small" > <asp:Label ID="lblContactHeaderHint" runat="server">(Show Details...)</asp:Label> </div> </div> </asp:Panel> <asp:Panel ID="ContactPanel" runat="server" CssClass="formPanel"> <table> <tr> <td width=200px>Address:</td> <td width=70%><asp:TextBox ID="txtAddress1" ReadOnly=false runat="server" MaxLength=200 width=70% /></td> </tr> <tr> <td>Address: </td> <td><asp:TextBox ID="txtAddress2" runat=server MaxLength=200 width=70%/></td> </tr> <tr> <td>form controls removed </td> <td></td> </tr> </table> </asp:Panel> </td> </tr> </table> <ajx:CollapsiblePanelExtender ID="cpeRes" runat="Server" TargetControlID="ResPanel" ExpandControlID="ResHeaderPanel" CollapseControlID="ResHeaderPanel" TextLabelID="lblResHeaderHint" ExpandedText=" " CollapsedText="(Click to Show Details...)" ImageControlID="imgResArrow" ExpandedImage="~/images/collapse.jpg" CollapsedImage="~/images/expand.jpg" EnableViewState=true SuppressPostBack="true" /> <ajx:CollapsiblePanelExtender ID="cpeContact" runat="Server" TargetControlID="ContactPanel" ExpandControlID="ContactHeaderPanel" CollapseControlID="ContactheaderPanel" TextLabelID="lblContactHeaderHint" ExpandedText=" " CollapsedText="(Click to Show Details...)" ImageControlID="imgContactArrow" ExpandedImage="~/images/collapse.jpg" CollapsedImage="~/images/expand.jpg" EnableViewState=true SuppressPostBack="true" /> </asp:Panel></div></asp:Content>
 
 
 -Steve 


I'm assuming your saying that when you open one, the other one closes. If so, try this: remove the "EnableViewState=true" from your code and wrap the entire thing in an update panel. I have similar yet I have no troubles with it but mine is wrapped in an update panel.


Thanks for the reply,

That is not quite what I was aiming for. I just wanted the state (open or closed) of the panels to be preserved after postbacks and navigation in my application.

I have a large form, that fills even a high res screen, I split the form into several collapsible panels, so that the user can show and hide the sections that are interesting. Then as the user navigates application records, and postbacks occur, I wish the state of each panel to be preserved.

Maybe I need to manually store the state to the Session and I am misunderstanding the scope of view state?


-Steve


If I understand correctly the panels are closed when you do a postback. This is because a postback reloads the controls. You want to do a partial postback, not a full postback. Therefore, wrap everything in an UpdatePanel, set the updatepanel's updatemode="conditional" and set the ScriptManager to enablepartialrendering="true"

This will cure the headache of a postback. Also with navigation it will have to be in updatepanels. Anything that does a postback must be eleminated and moved into the AJAX portion using update panels and such, otherwise the page will do a complete postback. Overall, the logic behind how things are to be setup with AJAX is a bit more work but the results is well worth it.

^_^


Thanks for the advice, this is the effect that I want to acheive, however I am using a Master page with content pages, linked to a site map based navigation. I trawled the web and could find no examples of the kind of site templete being used with AJAX.

Do have any advice for trying to achieve this? Otherwise the best solution would be to store the panels state to the Sessions, although this seems clunky and I would have thought that the controls would respect viewsate acress postbacks.

-Steve

Viewstate problem

hi

every one using ajax knows that viewstate problem exists in it.....

is there any remedy available for that problem???

What problem? If you use Atlas, its updatepanel will go back to the server and runs the page as it normally would, and send/get ViewState per update as well, I didn't see any problem~
when using the back button and front button u ll be not able to maintain the viewstate........

Ya.. this is true.. as commn;y ajax calls leave no histtory in browsers..

Here is a back button support.. works with the old ctp...

viewstate serialization and atlas

Just testing a little popup calendar user control making use of Atlas. I notice that when I serialize the viewstate unusually (I have a 'StorePage' class that stores the viewstate in the db, keyed on a GUID in a hidden field on the page), the atlas calendar popup fails.

Can I work around this? Do my Atlas pages need to be decended directly from the Page class, or is my GUID-keyed technique flawed?

The calendar uses an updatepanel.

Thanks,

John

Hi John,

Can you explain exactly what doesn't work? Are you registering the hidden field by using ClientScript.RegisterHiddenField?

All pages no matter what will derive from Page, and Atlas doesn't care if there are other intermediate classes in the way (almost all pages have intermediate classes anyway due to code-behind files).

I can't think of any specific reason why this wouldn't work off the top of my head.

Thanks,

Eilon

Viewstate verification failed - HELP my website is falling apart. Again :-(

I have a timer component that refreshes my page every minute but after a while it fails with the error "Viewstate verification failed". I left the page refreshing last night and it showed it stopped after 3 hours. The contents of the page haven't changed so I'm wondering if it is a timing issue with another component on my master page that has a javascript timer to which refreshes itself using callbacks.

The full error from my Event Viewer is:

Event Type: Information
Event Source: ASP.NET 2.0.50727.0
Event Category: Web Event
Event ID: 1316
Date: 15/02/2007
Time: 03:31:22
User: N/A
Computer: MAT
Description:
Event code: 4009
Event message: Viewstate verification failed. Reason: Viewstate was invalid.
Event time: 2/15/2007 3:31:22 a.m.
Event time (UTC): 2/14/2007 2:31:22 p.m.
Event ID: b68b7d7fa4d446b3adba40708b352b32
Event sequence: 341
Event occurrence: 1
Event detail code: 50204

Application information:
Application domain: /LM/W3SVC/1/Root/flo-1-128159266743963684
Trust level: Full
Application Virtual Path: /flo
Application Path: c:\inetpub\wwwroot\flo\
Machine name: MAT

Process information:
Process ID: 2308
Process name: aspnet_wp.exe
Account name: MAT\ASPNET

Request information:
Request URL:http://localhost/job_status.aspx
Request path: /job_status.aspx
User host address: 127.0.0.1
User: matthew
Is authenticated: True
Authentication Type: Forms
Thread account name: MAT\ASPNET

ViewStateException information:
Exception message: Invalid viewstate.
Client IP: 127.0.0.1
Port: 1349
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; InfoPath.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)
PersistedState: /wEWBQK9m9+mCQL20L6+CQLh8tHdBgLd/pFuArD90/EPqAe+PBf42BwApxmU14Oldo6DzQU=
Referer:http://localhost/job_status.aspx
Path: /job_status.aspx

Custom event details:

For more information, see Help and Support Center athttp://go.microsoft.com/fwlink/events.asp.

Any help would be appreciated.

Hi Matthew,

I remember some time ago to find a similar problem. It had to do with the fact that viewstate is saved in a hidden field at the end of the page, and continuous AJAX refreshes queued successive requests before they were finished, at the point where the request still had to reach the "end" of the page, where the ViewState resides. As you can see, the ViewState validator couldn't do it's work and, therefore, it threw an exception like the one you are having.

If you search the forum you may find that thread, as I haven't started it I have no easy way to point you to the link. I think I remember there was a workaround as well.

Sorry not to be more helpful, but maybe at least I gave a direction to start looking at.

Regards,

Juan


Thanks for the info. I have set up two almost duplicate copies of the site, one with buffering and one without to see if that is causing invalid data. If that doesn't work I'll look for the thread you mentioned.


Have you figured this out yet? I'm seeing this intermittently and am not sure where it's coming from.

Thanks!


I have managed to resolve this problem by not having multiple types of callback components, ie AJAX and custom made callback scripts.

What I did in the end was to setup a timer on the masterpage. On the content pages if I want update panels to update I add a trigger to the update panel that is pointing to the timer on the masterpage. Therefore evry minute the timer on the masterpage refreshes all updatepanels that are connected to it.

If you need more info let me know and i'll sort some code out for you.

Viewstate was invalid when using the back button

Ok, this is going to be difficult to explain but I'll do my best. So we have several pages that make significant use of update panels. So you can interact with the page and the update panel does its thing. Then you can click a link that takes you to a different page.

Now, what can possibly happen is this scenario where the user then hits the back button so they are back on the page with the update panel. But they go back to the page and the update panel has reverted to its original state. It doesn't look like what it looked like when they left the page.

If you then click on the page to cause the update panel to do its thing again, you get a "Viewstate verification failed. Reason: Viewstate was invalid." error.

Anyone have any thoughts on this?

Are there any events fired when the back button is pressed? Is there anyway when the back button is pressed that I can set the update panel to be the state that it was in when the user left?

Thanks a lot!

Hi,

ASP.NET Futures inlude special control to control browser history and restore AJAX pages when user clickcs BACK. I have never used it, but as far as I know it is what you are looking for. See:http://quickstarts.asp.net/Futures/ajax/doc/history.aspx

-yuriy
http://weblogs.asp.net/ysolodkyy


The history control works great while you remain on the same page. So you can bounce around within the update panel and then hit back to alter the state within the current page. However, if you navigate away from that page and then hit the back button to go back to your page with the update panel, that's where I'm running into my problem.