Choose a location:
As we know ViewState setting in ASP.NET has a hierarchical nature i.e. if the ViewState is disabled on the parent control; it cannot be enabled on any of its child controls. In other words Parent level ViewState setting has highest priority i.e. if we disable Parent level ViewState through EnableViewState= “False”, we can’t enable ViewState for any child control even if we try to set EnableViewState= “True” for child control. Now ASP.NET 4.0 has solved this problem.
ASP.NET 4.0 introduces a property ViewStateMode; with the help of it we can disable ViewState at a Parent level and can enable it for child control. In ASP.NET 4.0 ViewStateMode property accepts following values-
Let’s understand it.
Simply creates a demo web application with following HTML markup-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Sample.aspx.cs" Inherits="Sample" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lblDemo" runat="server" ></asp:Label> <asp:Button ID="btnPostback" runat="server" Text="Button" /> </div> </form> </body> </html>
Put following code in Page_Load method-
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { lblDemo.Text = DateTime.Now.ToString(); } }
Lets discuss some cases.
<%@ Page Language="C#" ViewStateMode="Enabled" AutoEventWireup="true" CodeFile="Sample.aspx.cs" Inherits="Sample" %> <asp:Label ID="lblDemo" runat="server" ViewStateMode="Disabled" ></asp:Label>
In this case ViewState does not persist after the post back showing that control’s ViewState is independent of its parent’s ViewState.
<%@ Page Language="C#" ViewStateMode="Disabled" AutoEventWireup="true" CodeFile="Sample.aspx.cs" Inherits="Sample" %> <asp:Label ID="lblDemo" runat="server" ViewStateMode="Enabled" ></asp:Label>
In this case ViewState persists after the post back again showing that control’s ViewState is independent of its parent’s ViewState.
<%@ Page Language="C#" ViewStateMode="Disabled" AutoEventWireup="true" CodeFile="Sample.aspx.cs" Inherits="Sample" %> <asp:Panel ID="pnlParent" runat="server" ViewStateMode="Enabled" > <asp:Label ID="lblDemo" runat="server" ViewStateMode="Inherit" ></asp:Label> </asp:Panel>
In this case ViewState persists after post back again as child control inherits its parent’s ViewStateMode.
So we have seen that we can set child control’s ViewStateMode irrespective of parent’s ViewStateMode or can inherits parent’s ViewStateMode in very simple manner. It’s a very good feature in ASP.NET 4.0. This feature improves performance of the page with lesser pains and provides more control.
What kind of email newsletter would you prefer to receive from CodeAsp.Net? 18