Latest web development tutorials

ASP.NET ViewState

By maintaining the object in your Web Form in ViewState (View State), you can save a lot of coding.


Maintain ViewState (View State)

In classic ASP, when a form is submitted, all form values ​​are cleared. Suppose you submit a form with a lot of information, and the server returns an error. You have to return to the form corrections. You click the Back button, and then what happened ...... all form values ​​are cleared, you have to start everything! Site does not maintain your ViewState.

ASP .NET in, when a form is submitted, the form together with the form values ​​appear together in the browser window. How to do it? This is because ASP .NET maintains your ViewState. ViewState will be submitted to the server when the page indicate its status. This state is through on every page with a <form runat = "server"> control the placement of a hidden field definition. 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 the ViewState is the default setting for ASP.NET Web Forms. If you do not want to maintain the ViewState, at the top of .aspx page that contains instructions <% @ Page EnableViewState = "false"%>, or add properties EnableViewState = "false" to any control.

Look at the following .aspx file. It demonstrates the "old" operating mode. When you click on the submit button, the form value will disappear:

Examples

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

The demonstration >>

Here is the new ASP .NET way. When you click on the submit button, the form value will not disappear:

Examples

Click on the example of the right frame to view the source code, you will see the ASP .NET has added a hidden field in the form to maintain the 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>

The demonstration >>