Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should EnableViewState be enabled on a server control?

Tags:

asp.net

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.

like image 314
Jack Avatar asked Jan 15 '09 22:01

Jack


People also ask

What is the use of EnableViewState?

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 .

Is ViewState enabled by default?

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.

What happens when ViewState disabled?

If you disable ViewState, and a page needs it, the page will no longer work.


1 Answers

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" 
like image 88
Ken Browning Avatar answered Nov 06 '22 19:11

Ken Browning