New features ViewState in ASP.Net.4

ViewState is one of the important factors if we start looking at improving the performance our asp.net site.  Till ASP.Net 3.x, we have EnableViewState property both at Page level and server control level to control the view state. Disabling the ViewState at page level will disable the viewstate to all the page controls. In order to improve the performance, one need to switch off the viewstate for individual control for which saving the viewstate is not necessary and hence disabling viewstate at page level is not a suitable option.  To overcome this difficulty, asp.net 4.0 added a new property to Page object and controls called ViewStateMode.

 This property can take 3 values,
1.      Enabled
This value will enable the view state. This is the default value for the Page object.
2.   Disabled
This value will disable the viewstate
3.   Inherit
      This value will make the control to inherit the setting of the parent. This is the default value for a control.With this property, we can disable the viewstate for the page and enable it for the control if only required.

Consider the following code,

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ViewStateTest.aspx.cs" ViewStateMode="Disabled" Inherits="ViewStateTest" %>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" ViewStateMode="Enabled" Text="Default Text"></asp:Label>
        <br />
         <asp:Label ID="Label2" runat="server" Text="Default Text"></asp:Label><asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
     </div>
    </form>

CodeBehind

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Label1.Text = "Text Assigned in CodeBehind";
            Label2.Text = "Text Assigned in CodeBehind";
        }
    }

When the page executed we will get the following output,
Text Assigned in CodeBehind
Text Assigned in CodeBehind 

When the button is clicked,
Text Assigned in CodeBehind
Default Text
 Since, the viewstate is disabled at page level (Page object) and the viewstate is enabled for “Label1” we will get the above output on Button click. Please note that if we have not set the value, the default will be “inherit” (for Label2).
Note
If we disabled the viewstate through EnableViewState property, setting any values for ViewStateMode property will make no impact.

No comments:

Post a Comment