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>