I have seen lots of confusion in various threads, that How and Why a textbox persists data even when View State is set to off. Even I was confused earlier but I tried to discover it and I found the root cause, so I am sharing it with you.
For that, first let’s see the page life cycle on postback.
Now let's first discuss about the View State, how View State works?
If View State is on for any control, during LoadViewstate
, the View State data that got saved last time, gets populated in the control. And in last, the SaveViewState
method of every control that is part of the control hiearchy, gets called and combined View State of all the controls gets base64 encoded and saved.
So as we know, the page is recreated every time page makes a trip to the server, the data persistence is done with the help of viewstate.
Now here the point that we are going to discuss, even if we set off the View State of some controls like textbox
, checkbox
, etc... the data persists during postback.
Let’s discuss it in a little detail, whenever a page is submitted or posted back to server, the entire form data is posted to the server as a collection with the request. The collection is in the form of NamedValue
collection and this collection has the mapping with uniqueid of the control and the value of the control. You can read the data from the form collection by using the following code snippet:
string textboxvalue = Request.Form[textbox1.UniqueID];
ASP.NET uses this primitive to update the control’s value. ASP.NET uses IPostBackDataHandler
for the controls that load the data from the form collection.
Actually all the controls which implement IPostbackdatahandler
, implement the method LoadPostData
and RaisePostDataChangedEvent
. But here, the key method is LoadPostData
, which returns true
if the posted value is changed from earlier value and updates it with posted value, else it returns false
. Let's see the sample code here:
public virtual bool LoadPostData(string uniqueId,
NameValueCollection postedCollection) {
String currentValue = this.Text;
String postedValue = postedCollection[uniqueId];
if (currentValue == null || !currentValue.Equals(postedValue)) {
this.Text = postedValue;
return true;
}
return false;
}
As from the Page Life Cycle, we can see LoadPostData
is called after the LoadViewState
, whether viewstate is on or not, it gets populated from the posted data. That’s why the data get persisted even if viewstate is set to off for few controls. Following is the complete list of the controls that implement IPostBackDataHandler
.
CheckBox
CheckBoxList
DropDownList
HtmlInputCheckBox
HtmlInputFile
HtmlInputHidden
HtmlInputImage
HtmlInputRadioButton
HtmlInputText
HtmlSelect
HtmlTextArea
ImageButton
ListBox
RadioButtonList
TextBox
I think this must have helped many of you overcome this hazy picture.
Thanks,
Brij