ViewState - how to persist state between two pages - asp.net

On page1.aspx i hava a textbox with id="tb1"
On page2.aspx I have a textbox with id="tb2"
page2.aspx is set as postbackurl for page1.aspx. For both labels enabl;eViewState is true.
Shouldn't the text I write in page1 also appear in the label on page2? Can I implement this without looking into Request headers, and setting the text myself?

ViewState is a blob of Javascript that is persisted for a single page, not across multiple. When you use the PostBackUrl property to post to a different page than the initial page, you need to perform your own validation, and pull property values from the controls on the "previous page":
// Get the value of TextBox1 from the page that
// posted to this page.
text = ((TextBox)PreviousPage.FindControl("tb1")).Text;
Also, ViewState is honored on a per-control basis so even if what you wanted to happen was possible, the fact that your TextBoxes have two different IDs would mean ViewState wouldn't be able to match them up...

Related

ViewState Management in ASP.Net

i was recently surfing the msdn for the session state management tools, i came accross viewstate, which can be used the retain the page or controls value accross the page postback, so i created a simple application, which contains a asp:textbox and asp:button now i made the EnableViewState="false" for textbox and run the page, entered some values and clicked on the button, the page postbacked but the value was retained, i thought that would be because the pages viewstate property is enabled, so i changed the EnableViewState="false" in the page directives, and run the page, still the textbox value was retained in the textbox accross the postback, can anyone tell me with small example how the does viewstate work in my scenario
ViewState can probably not be explained with a small example ;-)
I'd recommend to read this article: Truly Understanding ViewState
The TextBox is rendered as input control, so the value is post back and set again to the TextBox.
The viewstate have a meaning on the TextBox for the other attributes that you can set it pro grammatically, or in case that you make it hidden and you like to keep the content of it.

TextBox Text is empty on postback

I have a problem that occures from time to time but I can't figure out the reason why it's happening.
I have a txtFilter. I enter the value in textbox hit the asp:button that posts the form back to server and txtFilter.Text property is empty. The control where texbox resizes is added to the page dynamically but it depends on a request parameter so it's not the case that I'm not loadding some controls that were loaded before.
The strangest part in this situation is that even though txtFilter.Text is empty,
Request[txtFilter.Text.UniqueID] has the value that I entered.
Any ideas?
If you are dynamically creating/adding the textbox control you need to do it in page_init so it participates in the normal page event lifecycle. This link may help: http://support.microsoft.com/kb/317794
Request[controlid] will always contain the value that you entered since you are accessing the raw HTML form post data.

ASP.Net Web Form + Ajax Data lost on post back. Possible cause ? Ajax or changing visible property

I have two Repeater controls, each hosted in a user control. Both user controls are contained in the same aspx page. Only one User Control is visible at any one time. The repeaters are comprised of checkboxes, and text boxes for user input.
The aspx page is configured with an Ajax ScriptManager; and contains several Ajax UpdatePanels. These UpdatePanels result in partial page post backs when text is changed in a textbox control in controls on the aspx page (this is not the behaviour for the Repeaters in the User Controls). Through use of several AsyncPostBackTriggers, various controls contained in the other UpdatePanels on the page have their content refreshed in response to the partial page post backs they are configured be notified about.
Depending on a radio button group selection, I set the visible property to true or false – as appropriate for the User control containing a repeater control. The Repeater control is then populated with data using databinding. All of this works.
However, when the Submit button is clicked, the Repeater control contains no data.
Given that I am not dynamically adding the Controls containing the Repeater controls (but using Visible true / false). I would have thought that the State of the fields and the data in the visible control would be preserved during the post back.
The User Controls are contained within the UpdatePanel that contains the Submit Button.
I have explicitly Enabled View state without any effect.
Am I correct in assuming that I should not have to do any explicit handling of data changes the user makes (via client side script and manipulation of an Data Structure Representing the Repeater Data); and the View State should maintain the data I need to access on the server when submitted?
I do not believe that it is the User Control visible state changes that are causing the issue because when the page is initially loaded on of the User controls is populated with dummy rows (so it displays).
I am suspicious that because the visible state of the controls is changed during partial page post back, that the Page View State ends up with no knowledge of the User Control and therefore cannot track its data (or changes).
I have investigated a lot of similar sounding posts but so far do not feel that I have come across a solid explanation that can help me understand and fix the issue.
Hopefully someone can help.
I must be the only person who was unaware of the finer points of DataBind() method; be it called on a specific control being bound to data; or on the page itself. I hope the below helps others who find themselves in a position where data binding appears to be inexplicably lost'.
My problem was that my page was pretty complex. It has several User Controls on it. The problem was that in these User Controls, I was calling Page.DataBind() in the Page_Load event handler to 're-bind' the page data on PostBacks. This resulted in the Repeater control located on another User Control, to lose its data binding.
Removing the Page.DataBind method call from each of the User Controls on the Page_Load event handler method resolved the problem. It had nothing to do with Update panels / refreshes etc.

Why do some asp.net controls keep its state although its EnableViewState property is false?

Put a textbox, a checkbox and a button on a website.
Set the "EnableViewState" property of textbox and checkbox to false.
Write something into textbox and check the checkbox.
Click the button.
Why is the textbox still written and the checkbox checked after response?
Some things aren't totally dependent on ViewState. In the controls you listed, those values are available in the POST sent to the server, so they're gotten out of there and the controls restore their state that way.
Other things, like the text in a <asp:Label> for instance aren't sent back in any way, and they'll lose their data without ViewState. The same is true for other properties, like the styling of the textbox, etc...only it's value will be restored, because that's all that's sent back and as a result, all it's coded to grab and restore. If you were to say make it red, that would be lost on postback.
As a general rule, what a control can restore strictly from posted data will be restored on postback, everything else is lost.
Because HTML Controls are Stateless control. Therefore Microsoft provide a feature of ViewState that help when a user sends the data into server or after post back the value remain same. Therefore you have to set the property "EnableViewState" to True. By default, all the ASP.NET controls have their EnableViewState set to True

When should EnableViewState be enabled on a server control?

Is there any guideline or rule for when the view state should be enabled on a server control? And when it should not?
I was looking at this SqlDatasource example and noticed that the view state for the label control is not enabled:
<asp:Label ID="ErrorMessageLabel" EnableViewState="false" runat="server" />
Why isn't EnableViewState enabled on the label control? I know that enabling the view state carries some overhead so I would like to use it only when it is needed.
Here's a good rule of thumb: If you (1) change a property's value in the code-behind, and (2) need to know what value you set in a later postback without recalculating the value, then you need to use ViewState.
For example. In my page's markup I might have a Label control specified like this:
<asp:Label ID="TitleLabel" runat="server" Text="Update this Employee" />
Then in the Page_Load event I have this code:
If Not IsPostBack AndAlso myEmployeeObject.IsNew Then TitleLabel.Text = "Create a new Employee"
By changing the value of the Text property, I've introduced a new element into ViewState. If I get the value of the Label's Text property during any subsequent PostBack, the value will be "Create a new Employee".
Here's what I do when I set out to minimize the amount of ViewState used by my page. I enable tracing on the page. The trace output is added to the bottom of your page when its rendered in the browser. The trace output identifies every single server control on your page and includes how much ViewState (measured in bytes, I believe) each control stores. I use this information to calculate when I want to trade the overhead of ViewState for the overhead of recalculating values.
In my previous example, I would elect to recalculate the Label's Text property on every PostBack and stop storing the Text property in ViewState. This is how my updated markup would look:
<asp:Label ID="TitleLabel" runat="server" Text="Update this Employee" EnableViewState="false" />
And my updated Page_Load event:
If myEmployeeObject.IsNew Then TitleLabel.Text = "Create a new Employee"
Only time you should use viewstate is when you need to get the value of that sucker back on a postback or something. So for the label example you'd only need viewstate enabled if you had code that said something like
void Button1_Click()
{
label1.text += " more!";
}
without viewstate the postback couldn't figure out the contents of the label and you'd just get " more!" over and over with no append. try it.
Really, our the rule of thumb at my office is just turn it off at the page level and then enable it as you need it.
First understand the view state, here is a blog entry that might help.
Start developing your pages by disabling the viewstate at the page level. Most controls in asp .net 2.0 save state required for their functioning in the Control State thus disabling view state would not affect most controls.
For controls that do save data bound to them in the view state like List box, you can avoid the data from landing in the view state (which works fine for most use cases) by doing your binding on the PreInit event.
Other than that, if you don't have a third party control that needs it or so, the performance penalty you encur from using the view state far outweighs the promised preservation of state you get between postbacks.
And finally use tools that help you see the bytes going on in your page's view state. The ASP.NET View State helper and an add in into Fiddler which shows viewstate data would help you a lot in this respect.
only enableviewstate when you want to preserve the values across http requests, other than that keep it = false. also you dont have to enableviewstate to use a control.
Whenever you have a control on which the contents will be important (like a text box or drop list) you want to enable viewstate so that the content will available and update to date on a postback.
Anytype of control which outputs somewhat static text (stuff you are not getting back from the user) typically will not have viewstate enable. This minimizes the viewstate.
You need to make sure you understand the ViewState better. No blanket statement like "only enable the ViewState if you have to" will really make sense unless you do. Understand when the viewstate gets loaded/saved/dirtied.
here's one of the better articles i've seen
To be honest I can't think of any time you would want viewstate set to true for label controls. Its a quick way to make your w3wp.exe take up hoards of memory.

Resources