Tuesday, April 24, 2007

ASP.NET: TextBox and EnableViewState="False"
I've answered the question "I have disabled ViewState for my TextBox, why does TextBox retain its values when posting" so many times at ASP.NET Forums and newsgroups that I wanted to put something about it here too.

Answer:TextBox does not use ViewState as its only mechanism to retain state over postback. When rendered in HTML browser, TextBox is normal INPUT element from browser standpoint. When form is posted, the value of that INPUT element is posted along with the form. This happens whether you have ViewState enabled or disabled. Note that TextBox implements IPostBackDataHandler interface, so it loads the related, posted value from form post collection in its implementation of IPostBackDataHandler.LoadPostData.
Does TextBox use ViewState at all? Yes, it does. TextBox's Text property is implemented pretty much like this:

public string Text
{
get
{
string text=(string)ViewState["Text"];
return (text==null)? String.Empty : text;
}
set
{
ViewState["Text"]=value;
}
}
As you can see, value of Text property is actually stored to ViewState. So, how does TextBox use ViewState in this case? Well, in IPostBackDataHandler.LoadPostData TextBox uses ViewState as it compares the value of Text property to the value that is posted. As you probably guess, this is the case when TextBox's TextChanged event is raised if these values differ. If ViewState is disabled, Text property returns always String.Empty (it has not been assigned a value yet) and as a result posted value and Text property always differ and TextChanged event is raised every time.
After this, posted value is assigned to the Text property and rendered as the value of TextBox and things start over again. Note that Text property (ViewState collection actually) does keep its value during the same request even if ViewState is disabled. Disabling has impact on ViewState persistence not the functionality of ViewState collection. When ViewState is disabled, ViewState collection (System.Web.UI.StateBag) works similarly to the Context.Items collection. It is as it would be cleared for every request, but its values are valid during the same request.

Reference: http://aspadvice.com/blogs/joteke/archive/2004/03/15/2273.aspx

No comments: