17th Nov, 2007

A viewstate question you don’t know how to answer!

Which of the following has the largest viewstate? Label1 or Label2?

<asp:Label id=”label1″ runat=”server” Text=”abc” />
<asp:Label id=”label2″ runat=”server” Text=”sdfaskjdfasjdfkhksjahfd” />

If you think label2 viewstate is larger than label1 you are WRONG. The correct answer is - “they have the same viewstate”.

Viewstate has a mechanism called viewstate tracking. When the viewstate value changes after the control has been initialised, the statebag will be marked as dirty. Consequently, this will add the viewstate to the form’s __viewstate hidden field. If the control properties are set declaratively (ie, <asp:TextBox id=”test” runat=”server” Text=”test” />) or when they are initialised in the control’s OnInit event, tracking will not be enabled at that stage, hence they will not be marked as dirty and will not be added to the viewstate. This applies even when EnableViewState is true.

So lets assume you have declared this in an aspx page:

<asp:TextBox id=”test” runat=”server” Text=”test” />

If you change it’s value to “sdgfjskldfjklsjdlkfjlksdjfsk” in the Page_Load event you are effectively dirtying the stagebag which causes the value to be encoded and added to the __viewstate hidden field. This is a sin! Whenever you have default values you should set them declaratively or in the control’s OnInit event. This is because viewstate tracking is started after the control has been initialised.

Have you ever been to Malta? All you need to know is a click away! Malta Travel Guide, Bargain Accommodation in Malta, Malta Hotels

Leave a response

Your response:

Categories