ASP.NET - Maintaining ViewState

By maintaining the ViewState (view state) of objects in Web forms, you can save a lot of coding work.

Maintaining ViewState (View State)

When a form in classic ASP is submitted, all the form values will be cleared. Imagine that you submit a form with a lot of information, and the server returns an error. You will have to return to the form and correct the information. When you click the back button, what will happen... All the form values will be cleared, and you will have to start everything all over again. The site does not maintain your ViewState.

When a form in ASP.NET is submitted, the form will reappear along with all the form values. How is this done? This is because ASP.NET maintains your ViewState. ViewState indicates the state when the page is submitted to the server. By placing a hidden field in a <form runat="server"> control on each page, we can define the state of the page. The source code may look like this:

<form name="_ctl0" method="post" action="page.aspx" id="_ctl0">
<input type="hidden" name="__VIEWSTATE"
value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" />
.....some code
</form>

Maintaining ViewState is the default setting for ASP.NET Web forms. If you do not want to maintain ViewState, include the instruction at the top of the .aspx page: <%@ Page EnableViewState="false" %> or add the property: EnableViewState="false" to any control.

Please see the following .aspx file. It demonstrates the old running method. When you click the submit button, the form values will disappear:

<html>
<body>
<form action="demo_classicasp.aspx" method="post">
Your name: <input type="text" name="fname" size="20">
<input type="submit" value="Submit">
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!")
End If
%>
</body>
</html>

Display This Example

This is the new ASP .NET way. When you click the submit button, the form values will not disappear:

<script runat="server">
Sub submit(sender As Object, e As EventArgs)
lbl1.Text="Hello " & txt1.Text & "!"
End Sub
</script>
<html>
<body>
<form runat="server">
Your name: <asp:TextBox id="txt1" runat="server" />
<asp:Button OnClick="submit" Text="Submit" runat="server" />
<p><asp:Label id="lbl1" runat="server" /></p>
</form>
</body>
</html>

Display This Example (Click 'View Original Document' in the right frame to see that ASP .NET has added a hidden field to the form, so that ViewState can be maintained.)