ASP.NET Web Forms - Maintaining ViewState
ViewState is based on webform. Set runat = "server" in the web form control attribute. This control will be attached with a hidden attribute _ViewState. _ViewState stores the status values of all controls in ViewState. This section introduces you to how ASP.NET maintains ViewState.
By maintaining the ViewState of objects in your Web Form, you can save yourself a lot of coding work.
In classic ASP, when a form is submitted, all form values are cleared. Let's say you submit a form with a lot of information and the server returns an error. You will have to go back to the form to correct the information. You hit the back button and what happens...all the form values are cleared and you have to start everything over again! The site is not maintaining your ViewState.
In ASP .NET, when a form is submitted, the form appears in the browser window along with the form values. How? This 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 want not 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.
Please see the .aspx file below. It demonstrates the "old" way of operating. 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 fnamefname=Request.Form("fname")If fname<>"" ThenResponse.Write("Hello " & fname & "!")End If%></body></html>
Here's the new ASP .NET way. When you click the submit button, the form values do not disappear:
Click View Source in the right frame of the instance 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>