Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

ASP.NET ViewState


May 12, 2021 ASP.NET


Table of contents


ASP.NET Web Forms - Maintain ViewState

ViewState is webform-based, setting runat to "server" at the property of the web form control, which is attached to a hidden property _ViewState,_ViewState holds the state values of all controls in ViewState.

This section introduces you to How ASP .NET maintains ViewState.

By maintaining the viewState of an object in your web Form, you can save a lot of coding.


Maintain ViewState (View State)

In a classic ASP, when a form is submitted, all form values are emptied. S uppose you submit a form with a lot of information and the server returns an error. Y ou have to go back to the form to correct the information. Y ou click the back button and then what happens... A ll form values are emptied and you have to start all over again! The site does not maintain your ViewState.

In ASP .NET, when a form is submitted, the form appears in the browser window along with the form value. H ow do you do that? T his is because ASP .NET maintains your ViewState. V iewState indicates the state of the page when it is submitted to the server. T his state is defined by placing a hidden domain on each page with the .lt;form runat"server" control. The source code looks like this:

<form name="_ctl0" method="post" action="page.aspx" id="_ctl0">
<input type="hidden" name="__VIEWSTATE"
value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" />

.....some code

</form>

Maintaining ViewState is ASP.NET setting for Web Forms. If you want to maintain ViewState, include the instructions at the top of the .aspx page, or add the property EnableViewState to any control.

Please see the .aspx file below. I t demonstrates how "old" works. W hen you click the submit button, the form value disappears:

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

Demo Examples . . .

Here's the new ASP .NET approach. When you click the submit button, the form value does not disappear:

Click on the frame to the right of the instance to view the source code and you'll 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>

Demo Examples . . .