Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

ASP.NET ViewState

ASP.NET Web Forms - Maintaining ViewState


By maintaining the ViewState (view state) of objects in your Web Form, you can save a lot of coding work.


Maintaining ViewState

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 go back to the form to correct the information. You click the back button, and then what happens... all form values are cleared, and you have to start everything all over again! The site did not maintain your ViewState.

In ASP.NET, when a form is submitted, the form appears in the browser window together with its form values. How is this done? This is because ASP.NET maintains your ViewState. ViewState indicates its state when the page is submitted to the server. This state is defined by placing a hidden field on each page with the

control. The source code is shown below:

value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" />

.....some code

Maintaining ViewState is the default setting of ASP.NET Web Forms. If you do not want 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 look at the .aspx file below. It demonstrates the "old" way of working. When you click the submit button, the form values will disappear:

Example

Your name:

<%

dim fname

fname=Request.Form("fname")

If fname<>"" Then

Response.Write("Hello " & fname & "!")

End If

%>

Demo Example »

Below is the new ASP.NET way. When you click the submit button, the form values will not disappear:

Example

Click "view source" in the right frame of the example, and you will see that ASP.NET has added a hidden field to the form to maintain the ViewState.

Your name:

Demo Example »