Friday 26 August 2011

ASP .NET Maintaining the ViewState


You may save a lot of coding by maintaining the ViewState of the objects in your Web Form.

Maintaining the ViewState

When a form is submitted in classic ASP, all form values are cleared. Suppose
you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form and correct the information. You click the back button, and what happens.......ALL form values are CLEARED, and you will have to start all over again! The site did not maintain your ViewState.
When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat="server"> control. 



Maintaining the ViewState is the default setting for ASP.NET Web Forms. If you want to NOT maintain the ViewState, include the directive <%@ Page EnableViewState="false" %> at the top of an .aspx page or add the attribute EnableViewState="false" to any control.
Look at the following .aspx file. It demonstrates the "old" way to do it. When you click on the submit button, the form value will disappear:

<%@ Page Language="vb" EnableViewState="True" %>
<html>
   <head>
      <title></title>
      <script runat="server">
         Sub Page_Load()
            If Page.EnableViewState = True Then
               Message.Text = "ViewState is enabled."
            Else
               Message.Text = "ViewState is disabled."
            End If
         End Sub
      </script>
   </head>
<body>
   <form runat="server">
      <asp:label id="Message" runat="server"/>
   </form>
</body>
</html>