Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Control.ViewStateMode Property

0.00/5 (No votes)
5 Jun 2013 1  
View state is where the status of the page is saved when it is submitted to the server. View state is saved as hidden controls, within the form. View

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

View state is where the status of the page is saved when it is submitted to the server. View state is saved as hidden controls, within the form. View state stores value of each page controls as Base64 encoded strings.  

We can make a page not to store view state by adding EnableViewState in the <%@ Page %> tag.

Eg : <%@ Page Language="C#" EnableViewState="false" %>

The default value for EnableViewState is “true”.

 From ASP.Net 4.0, we get a new property for server controls – ViewStateMode, which can have value as “Enabled, Disabled and Inherit”. The default value of ViewStateMode is “Inherit” for controls and “Enabled” for page.

 To enable view state for just one (or selected few) controls, Set 

<%@ Page Language="C#" EnableViewState="true" ViewStateMode="Disabled" %>

And then set ViewStateMode="Enabled" only for the selected controls, which should store view state.  The rest of the controls will have the default value as ViewStateMode="Inherit", which will inherit from <%@ Page %> and hence, will be disabled

This will keep unwanted data not being saved as view state while postbacks.

Try out this code

Default.aspx

<%@ Page Language="C#" EnableViewState="true" ViewStateMode="Disabled"%>

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            lblInherit.Text = "Inherited Label, Value for view state";

            lblEnabled.Text = "Enabled Label, Value for view state";

        }

    }

</script>

<html>

<body>

    <form id="form1" runat="server"> 

        <!--will not retain its value after postback -->

        <asp:Label ID="lblInherit" runat="server" Text="Inherited Label, Will not store view state"></asp:Label> <br />

 

        <!-- -will  retain its value after postback -->

        <asp:Label ID="lblEnabled" ViewStateMode="Enabled" runat="server" Text="This will store Viewstate"></asp:Label> <br />

 

        <asp:Button ID="btnPostback" runat="server" Text="PostBack" />

     </form>

</body>

</html>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here