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.
View state enables a server control to maintain its state across HTTP requests. View state for a control is enabled if all of the following conditions are met: The EnableViewState property for the page is set to true . The EnableViewState property for the control is set to true .
By default, ViewState is enabled for all server controls. ViewState can be enabled and disabled in any of the following ways: Control Level. Page Level.
If you disable ViewState, and a page needs it, the page will no longer work.
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"
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