ASP.NET Web Forms - Maintain ViewState


By maintaining the ViewState of objects in your Web Form, you can save a lot of coding work.


Maintaining ViewState

In classic ASP, when a form is submitted, all form values are cleared. Suppose you submitted a form with a large amount of information, and the server returned an error. You have to go back to the form to correct the information. You click the back button, and then what happens... all form values are cleared, and you have to start everything all over again! The site did not maintain your ViewState.

In ASP.NET, when a form is submitted, the form appears in the browser window along with the form values. How is this done? It is because ASP.NET maintains your ViewState. ViewState indicates the state of the page when it is submitted to the server. This state is defined by placing a hidden field on every page with a <form runat="server"> control. The source code is as follows:

<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 directive <%@ Page EnableViewState="false" %> at the top of the .aspx page, or add the attribute EnableViewState="false" to any control.

Look at the following .aspx file. It demonstrates the "old" way of doing things. When you click the submit button, the form values will disappear:

Example

<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>

Show example »

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

Example

Click "View Source" in the right frame of the example, and you will see that ASP.NET has added a hidden field to the form to maintain ViewState.

<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>

Show example »
Other Extensions