Question reg. ASP.NET ViewState - asp.net

I've been going through this excellent article http://msdn.microsoft.com/en-us/library/ms972976.aspx that says ViewState is not responsible for form fields to retain their values between postbacks. So form fields values are never stored in ViewState?
EDITED: What I mean form fields are ASP.NET controls like TextBox, Dropdownlist etc.
EDITED: If an user enters a value in an ASP.NET textbox and submit the form, the new page still has the textbox with that value I was thinking this is because of ViewState but the article says it's not so!

As you say, form values are NOT stored in the viewstate. The reason that (for example) the text of a TextBox control is retained between two postbacks is because it implements the IPostBackDataHandler-contract and automatically maps the keys in the Request.Form-collection to the appropriate properties of the control. These two mechanisms are often confused.
See http://www.mikesdotnetting.com/Article/65/ViewState-form-fields-labels-and-Javascript for a good explanation.

Text fields don't carry their value in ViewState because their value is explicitly sent through the HTTP POST (See Request.Form) and restored to the control before Page_Load.
DropDownLists do use ViewState to store their contents.

only Asp.Net Control will stored in the ViewState. No html fields.
So
<asp:TextBox id="tb1" runat="server" />
will work and
<input type="text" id="tb1" />
will not work.

So form fields values are never stored in ViewState?
As stated by dknaack: No
But you may also want to have a look at ControlState since ViewState can be disabled.

The point of viewstate is to track the "change" in your webcontrols. It's your responsibility as a developer to ensure that the "initial" state of your controls is recreated each page load. Then the asp .net mechanism determines the change that occurred during a postback scenario to decide which events should be fired on the server side.
For an overview of how the ASP .Net postback mechanism works and where Viewstate fits in have a look at this question I originally asked on SO;
How does Postback Work?

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.

Viewstate vs Postback

I sort of answered my own question I think but I want to make sure I am understanding correctly. I initially thought that when a user provided values in a form, that on postback the values were submitted as part of the Viewstate, because TextBox.Text is part of the viewstate. Now I have found that user supplied values actually aren't applied to the controls until after the OnLoad event. This confused me because I thought that viewstate was loaded into the controls before OnLoad(or when calling Controls.Add()). I have gone over the documentation on page and control lifecycles a few times and I am just now realizing that there was a different step for handling postback data(this step didn't appear in a lot of documentation :(
1) So postback data, the values user's type into the fields, is applied after the OnLoad event, and Viewstate data is applied just before the OnLoad event?
2) So essentially all this means is that on postback the server gets two values for a TextBox.Text property, the one in Viewstate, which is like the "old" value from the previous request, and the new value supplied by the user in the form?
3) Does the .net framework apply postback data the same was as Viewstate, in that it finds the appropriate control via it's ID property? This is important because I am creating controls dynamically and I may even have forms that change structure overtime and need to think about how I handle ID's. So far I haven't been setting the ID property and everything works fine but things may be more complicated later on.
4) Does viewstate data ever get modified at all on client side? Or is the viewstate identical to what was sent by the server in the previous request(assuming no tampering)? My impression used to be that the server encoded all the control properties into the viewstate, and on the client side when the user submitted the form, the viewstate field was decoded, modified, encoded, and submitted to the server with modifications. I assumed there was a bunch of javascript doing all this for me. Now I think I had it all wrong. Instead it seems that the Viewstate never changes on client side, and all the client changes are in the postback data such that the next request the server loads viewstate, loads postback, and provides a new updated viewstate in the next response?
1) Both are loaded before Load
2) Basically, yes
3) ViewState is applied first, then Post Data
To quote Scott Mitchell(see below)
dynamically added controls must be
programmatically added to the Web page
on each and every page visit. The best
time to add these controls is during
the initialization stage of the page
life cycle, which occurs before the
load view state stage. That is, we
want to have the control hierarchy
complete before the load view state
stage arrives. For this reason, it is
best to create an event handler for
the Page class's Init event in your
code-behind class, and add your
dynamic controls there.
4) Unless you're doing something way outside of the box, ViewState is never modified client-side. "ViewState" is an HTML form field and is processed on the server side.
Here's a few images from Understanding ASP.NET View State by Scott Mitchell that may help you.
(source: microsoft.com)
(source: microsoft.com)
Bonus Reading Material: http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx
My impression used to be that the server encoded all the control
properties into the viewstate, and on the client side when the user
submitted the form, the viewstate field was decoded, modified,
encoded, and submitted to the server with modifications.
No, the point of the ViewState is simply to preserve the state of the page since the last "Save View State" page event, i.e. that event occurs shortly before the page is rendered to the client.
When the client makes selections to a dropdown box or changes text in a textbox the hidden ViewState property, which exists on the client page as a static HTML tag, is not dynamically changing / encoding those values, it remains the same as when the page was originally rendered.
So how is the new state of the page being preserved, i.e. how are user dropdown selections and text box values retained in ASP controls? Those dropdown selections and text box values are captured in Post Back data.
A server control can indicate that it is interested in examining the posted back data by implementing the IPostBackDataHandler interface. In this stage in the page life cycle, the Page class enumerates the posted back form fields, and searches for the corresponding server control. If it finds the control, it checks to see if the control implements the IPostBackDataHandler interface. If it does, it hands off the appropriate postback data to the server control by calling the control's LoadPostData() method. The server control would then update its state based on this postback data.
- Scott Mitchell

ASP.NET How ViewState works

I have a textbox and button on my .aspx page. The EnableViewState property of the textbox is set to false. But when I enter some text in the textbox and click the button the entered text is still present in the textbox. I expect the textbox to be blank since EnableViewState is set to false. Am I missing something?
Please check this Code Project article to better understand ViewState and Postback Data.
It is something like :
Why some controls retain values
even after disabling the ViewState
while others do not?
The answer is Controls which
implements IPostBackEventHandler IPostBackDataHandler like
Textbox, Checkbox, etc. will retain
the state even after disabling the
viewstate. The reason is during the
Load Postback Data stage, these
controls will get state information
from Posted back form.
But controls like label which do not
implement IPostBackEventHandler IPostBackDataHandler will
not get any state information from
posted back data and hence depend
entirely on viewstate to maintain the
state.
Below is related paragraph to your question.
In page life cycle, two events are
associated with ViewState:
Load View State: This stage follows the initialization stage of
page lifecycle. During this stage,
ViewState information saved in the
previous postback is loaded into
controls. As there is no need to check
and load previous data, when the page
is loaded for the first time this
stage will not happen. On subsequent
postback of the page as there may be
previous data for the controls, the
page will go through this stage.
Save View State: This stage precedes the render stage of the page.
During this stage, current state
(value) of controls is serialized into
64 bit encoded string and persisted in
the hidden control (__ViewState) in
the page.
Load Postback Data stage: Though this stage has nothing to do with
ViewState, it causes most of the
misconception among developers. This
stage only happens when the page has
been posted back. ASP.NET controls
which implement IPostBackEventHandler IPostBackDataHandler
will update its value (state) from the
appropriate postback data. The
important things to note about this
stage are as follows:
State (value) of controls are NOT retrieved from ViewState but from
posted back form.
Page class will hand over the posted back data to only those
controls which implement
IPostBackEventHandler IPostBackDataHandler.
This stage follows the Load View State stage, in other words state of
controls set during the Load View
State stage will be overwritten in
this stage.
This is by design
The following server controls persist their information across requests even when the control ViewState (the EnableViewState attribute) is set to False:
* The TextBox control.
* The CheckBox control.
* The RadioButton control.
This behavior occurs because the ViewState of a control is only one of the methods that are used to persist a control's attributes across requests. In the server controls that are mentioned in the "Symptoms" section, attributes that are not normally posted to the server through the form-get or the form-post are handled by the ViewState. These values include attributes of the control, such as BackColor. Attributes that are normally posted to the server are handled by the IPostBackDataHandler interface. An example of such an attribute is the checked attribute of the CheckBox control.
Also read this article
ASP.NET: TextBox and EnableViewState="False"
For understanding of Viewstate I don't think there is a better article than MSDN
Understanding ASP.NET View State
Take a look at Server controls persist their state when EnableViewState is set to False
The following server controls persist their information across requests even when the control ViewState (the EnableViewState attribute) is set to False:
The TextBox control.
The CheckBox control.
The RadioButton control.
This behavior occurs because the ViewState of a control is only one of the methods that are used to persist a control's attributes across requests. In the server controls that are mentioned, attributes that are not normally posted to the server through the form-get or the form-post are handled by the ViewState. These values include attributes of the control, such as BackColor.
Attributes that are normally posted to the server are handled by the IPostBackDataHandler interface. An example of such an attribute is the checked attribute of the CheckBox control.
Example: Consider backcolor setting programmatically. On postback, if viewstate is switched off, the background color of the Textbox control is lost. However, the text value of the control is maintained.
Note: If the backcolor was set directly in markup rather than in code behind, it would have persisted.
<form id="form1" runat="server">
<asp:TextBox ID="Textbox1" runat="server" EnableViewState="false"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" EnableViewState="false" />
</form>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.Textbox1.BackColor = Color.Yellow;
}
}
Following is from Understanding ASP.NET View State:
It is a common misconception among developers that view state is somehow responsible for having TextBoxes, CheckBoxes, DropDownLists, and other Web controls remember their values across postback. This is not the case, as the values are identified via posted back form field values, and assigned in the LoadPostData() method for those controls that implement IPostBackDataHandler.
A server control can indicate that it is interested in examining the posted back data by implementing the IPostBackDataHandler interface. In this stage in the page life cycle, the Page class enumerates the posted back form fields, and searches for the corresponding server control. If it finds the control, it checks to see if the control implements the IPostBackDataHandler interface. If it does, it hands off the appropriate postback data to the server control by calling the control's LoadPostData() method. The server control would then update its state based on this postback data.
Also refer following
View State for TextBox and other controls that implement IPostBackDataHandler
How do I disable viewstate for a specific control?

Gridview ControlState very large even when viewstate disabled and not using DataKeyNames

I have an asp:Gridview bound to an asp:ObjectDataSource. I have disabled the ViewState on the GridView, and have not set the DataKeyNames property. I have about 10 BoundFields and a few TemplateFields. These TemplateFields are not bound to server controls but to an anchor tag or to an img tag.
However, at runtime, when I switch on page tracing I see that the ControlState of the Gridview varies between 7 and 12K for displaying just 14 rows of data. (View source on the rendered page also gives a same long string in the __VIEWSTATE hidden field). I do not understand why this happens as I have enableViewState="false" on the gridview and, as said above, I am not using DataKeyNames. So, where is this Gridview ControlState coming from and is there a way to get rid of it?
Thanks in advance,
Tim
i think its normal because:
control state cannot be disabled, Control state is designed for storing a control's essential data (such as a pager control's page number) that must be available on postback to enable the control to function even when view state has been disabled
note: By default, the ASP.NET page framework stores control state in the page in the same hidden element in which it stores view state. Even if view state is disabled microsoft said
that mean you actually saw the data of ControlState in _ViewState field which is ok
because as microsoft said the ControlState of the control stored in viewstate even if you disable ViewState
If you're disabling viewstate, not using any postback controls within the gridview, and not doing paging/sorting, then you're probably better off using a repeater. Repeaters don't have to be placed inside a tag. So, the control state won't be an issue.
If you're using .net 3.5 you could also investigate using the ListView, which to me seems like a repeater / gridview hybrid.
This article says that control state is actually stored in the __VIEWSTATE in a HybridDictionary.
Also, these articles say that even though you can set EnableViewState=false, you can never turn off ControlState (which is the point - so clients can't break your application):
Control State vs. View State Example
ASP.NET State Management Overview
ASP.NET State Management Recommendations

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