When EnableViewstate = false
and I do postback, my textbox control retains the text value but label control does not. I am changing the text for both label and textbox on a button's click event.
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "Message Changed";
Label1.Text = "Message Changed";
}
There is another button my page for just postback.
Also if I do no need viewstate for this control, then is there a list of all the controls that don't need the viewstate?
All controls which implement IPostBackDataHandler
load their values even if ViewState is off. Note that events like TextChanged
and other properties like ForeColor
don't work when ViewState is disabled.
Here's a list of controls which implement IPostBackDataHandler
Why textbox persists data during postback even if View State set to off
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
//Reading textbox value from the form collection
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.
ViewState
is a messy hack to persist data between requests. The web is stateless and ViewState
tries to make it appear stateful.
I believe the TextBox
(and other <input/>
controls) keep their value without ViewState
because their values are POSTed in a form, while Label
(<span/>
) values are not. See @Tim Schmelter's answer for more on this.
Many Web Forms developers that care about page size will disable ViewState
globally and only enable it for specific controls. If you use standard paging in a GridView
, for example, you will need ViewState
so that ASP.NET knows what page number the user clicked. You could use custom paging and use actual links for the page numbers and then turn on off ViewState
.
It's an interesting task to use Web Forms without ViewState
as you lose a lot of the easy to use features of server controls but gain much more in control of your markup and state. However, it's my opinion that if you want that much control, you should consider using MVC instead of Web Forms.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With