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:
Then in the Page_Load event I have this code:
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:
And my updated Page_Load event: