Web Pages Tutor...login
Web Pages Tutorial
author:php.cn  update time:2022-04-11 14:20:28

Web Forms ViewState


ASP.NET Web Forms - Maintaining ViewState


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


Maintain ViewState (View State)

In classic ASP, when a form is submitted, all form values ​​will be 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 property 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:

Instance

<!DOCTYPE html>
<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>

Run Instance»

Click "Run" Example" button to view online examples

The following is the new ASP .NET method. When you click the submit button, the form values ​​will 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.

Instance

<script  runat="server">
Sub submit(sender As Object, e As EventArgs)
lbl1.Text="Hello " & txt1.Text & "!"
End Sub
</script>

<!DOCTYPE html>
<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>

Run Instance»

Click the "Run Instance" button to view the online instance


php.cn