воскресенье, 30 августа 2009 г.

Controlling View State using the ViewStateMode Property

One of the most complained thing in ASP.NET Webform is the growing viewstate which becomes a concern for performance. While earlier you can set the EnableViewState property to true or false, post that, all the controls, by default inherit and even if you set it to enabled at control level, the behaviour was inconsistent.With ASP.NET 4.0, the ViewStateMode property helps to determine for every control, whether the ViewState should be enabled, disabled or inherited accordingly. Ex.-

<asp:Panel ID="pnlViewState" runat="server" ViewStateMode="Disabled"> Disabled: <asp:Label ID="label1" runat="server" Text="Value set in markup" ViewStateMode="Inherit" /><br /> Enabled: <asp:Label ID="label2" runat="server" Text="Value set in markup" ViewStateMode="Enabled" /> <hr />

In the code-behind

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
label1.Text = "Value set in code behind";
label2.Text = "Value set in code behind";
}
}

When you run the above page, you can find that the intial value for both the labels is set to “Value set in code behind” whereas after clicking on the button (postback), the value of label1 changes to “Value set in markup” whereas the value of label2 remains unchanged. As you can see, the Panel which holds both these lables has ViewStateMode set to Disabled and label1 is inherting the mode (this is the default if not specified) and label2 has it enabled. That is the reason label2 maintains viewstate while label1 loses it.While it is arguably possible using the simple EnableViewState property earlier, it was never consistent. Considering the fact that in most of our performance sessions, we talk about disabling viewstate and then enabling it at control level while it doesnt work, this ViewStateMode is a welcome architectural change to improve performance.

Комментариев нет: