Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>For example. In my page's markup I might have a Label control specified like this:</p> <pre><code>&lt;asp:Label ID="TitleLabel" runat="server" Text="Update this Employee" /&gt; </code></pre> <p>Then in the Page_Load event I have this code:</p> <pre><code>If Not IsPostBack AndAlso myEmployeeObject.IsNew Then TitleLabel.Text = "Create a new Employee" </code></pre> <p>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".</p> <p>Here's what I do when I set out to minimize the amount of ViewState used by my page. I <a href="http://msdn.microsoft.com/en-us/library/ms972204.aspx" rel="noreferrer">enable tracing</a> 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.</p> <p>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:</p> <pre><code>&lt;asp:Label ID="TitleLabel" runat="server" Text="Update this Employee" EnableViewState="false" /&gt; </code></pre> <p>And my updated Page_Load event:</p> <pre><code>If myEmployeeObject.IsNew Then TitleLabel.Text = "Create a new Employee" </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload