- 1. Introduction to ViewState & Postback
- 2. About the Example
- 4. The ‘Add Button’ Click Handler
- 5. Page Behavior – “EnableViewState” Turned OFF
- 5.3 Second Data Post & Importance of ViewState
- 6. Page Behavior – “EnableViewState” Turned ON
- 7. Summary
1. Introduction to ViewState & Postback
In ASP.Net, Page-Level ViewState plays an important role when post-back of a page happens for multiple times. When data filled in a Web Form go to the server and returns to the same browser session, we can call that as Post-Back. In this Asp.Net example, we will experiment how a web server preserves the Form data. In addition, we will also learn the ViewState which is a form-level property. Note, this article was moved from My Hub Pages Network. You can read more article from my Hub Pages Network.
2. About the Example
The below screenshot shows the Asp.Net page which we will create to study the ViewState property.
2.1 User Interaction and Server Response
Here, the user will input the data in the Product Name and Quantity text boxes. When the user clicks the Add button, the browser posts the date to the server and server sends back the response to the same page. The Asp.Net Web Server populates the Label in the page’s bottom before sending the response (Post-Back) back to the browser session.
2.2 Multiple Post-Back From This Example
The goal is to list the Products and Quantity given by the User. For example, the user can enter Product along with Quantity and hits the Add button to Add the product in the shopping cart. Let us say the user adds three products like this and this will cause multiple Post-backs. We will list all three products in the Label. This will make us understand:
- What is the role of ViewState in Post-back?
- How form level data is preserved by Server?
- What is the role of a hidden field?
2.3 Create WebSite Form
To proceed with the example, create an ASP.Net Website project. The steps are below:
- Open Visual Studio (We Used 2005) and Navigate File->New->web site.
- Select Asp.Net WebSite from the template. Make sure language is Visual C#, and then Click OK.
- Rename the File ‘Default.Aspx’ to ‘ViewStateTracking.Aspx’.
- Design the Form in ViewStateTracking.Aspx page as per the picture in this section.
The below table shows Control Name, Type and its property with a new value. We can use this to setup the controls on the form.
|Control Name, Type||Properties|
|Label1, Label||Text=Product Name:|
|Label2, Label||Text=Quantity :|
|Label3, Label||ForeColor=#FF8080, Text=List Of Products Ready for Check-Out|
After designing the form, we have to set up a property called enableviewstate and set its value to “false”. Below is the Screenshot for the Steps:
4. The ‘Add Button’ Click Handler
Now, we will add the Click event handler for the Add Button of our Asp.Net web page. To do that, we have to double-click the Add button from the Design Tab. Visual studio will Bring you to C# Code and we have to edit the handler code as shown in the below code snippet:
The handler code concatenates the Product (Marked as 2) and its Quantity (Marked as 3) from the corresponding Text Boxes and assigns that to the Label Control (Marked as 1). Note the usage of ‘Line Break’ (Marked as 4) at the end of the string addition. This is to show each product on a different line. Compile and build the code and then view the page in a browser. You can do that by right-clicking the Page and choosing ‘View in Browser’ from the Context Menu.
5. Page Behavior – “EnableViewState” Turned OFF
Once the Page is opened in the Browser, the initial page looks like what is shown in the top-left corner of the screenshot below.
5.2.2 Server Handles Button Click
After Applying the defaults, Server overrides the defaults with the data received from the client browser. The Asp.Net Web Server then handles the events produced on the client’s browser. In our case, the server runs the btnAdd_Click handler. Note that the button is clicked on the Browser and handler runs on the server.
5.2.3 Browser Renders Post-Back Data
By the time Button click handler runs on the server, the defaults are already got replaced by the user filled Form Field Data. In our case it is Product Name and Quantity. The handler performs string concatenation and post-backs the data back to the browser to render it. The Browser renders the lblListOfProduct with “Product No 1232-15”. It also renders other Form Field Data which is not changed on the server. Note, the server doesn’t bother about the EnableViewState property as we turned it OFF.
5.3 Second Data Post & Importance of ViewState
5.3.1 Second Data Post to Server
As part of Second Data Post which is shown as Data Post 02 in the picture, we are entering Product Name as ‘Product No 3215’ and Quantity as 22 and then Hitting the Add button. We are doing this in the same browser session after post-back happened from the ASP.Net server. The browser posts these Form Field Data to the server for the second time. Does this Second Data Post, posts the Label Content “Product No 1232-15” to Server? Because in our first post that is what we sent to the server. The answer is No. Here comes the role of EnableViewState Property. Remember, we turned it OFF for now.
5.3.2 Previous Post Value? I Don’t Remember That – Server Says
Again, Does Data Post 02 posts “Product No 1232-15” to Server? The answer is No as it is not filled by the User. Moreover, the browser already rendered it which is part of the Previous Post-back. Now, for this current post, when data received by the Server which is altogether a new post for it. It doesn’t remember the Label Text from the previous Post (Data Post 01) and because of that it ends up rendering “Product No 3215-22” in the lblListOfProducts. This is not the behavior we need for that Label, Right? We want to display products gets piled up on each Add click & as a result showing check-out list for the User.
OK. Now it is time to study the behavior of the server with EnableViewState is true.
6. Page Behavior – “EnableViewState” Turned ON
In the past section, we saw the need for ViewState by posting the Data to the Web Server for three times. Now we will turn ON the ViewState by setting the EnableViewState Property to True. One can refer the picture in Section 3 for a reference.
Now, we we will have a look at the Picture below:
6.1 Http GET Request to Server
Here, we have done same three post-back like we did before. But, in the Picture, we have taken only two for our analysis. When we browse our example page, we are making an “Http Get” request. Since we are requesting the web page from the server for the first time, we call this as Http Get. This action is started by the client browser which is requesting a resource that is A Web Page from the Web Server.
6.2 Multiple Server Postback With ViewState Enabled
6.2.1 PostBack Round-Trip 1
The user at the client browser fills the form field data (Two Text boxes) and clicks the Add button and this makes an “HTTP Post” and in the picture, it is shown as Post 01. The Web Server responds to the Add Click Event and calls the C-Sharp Event Handler for the Button Click Event. In the Button Click Event, we are forming the content for our lblListOfProducts Label.
Now, as EnableViewState is turned ON, the Web Server packs the Page Level View State information as Hidden Form Field Data and performs the Post-Back. The picture shows this as Post-Back 01. Here, ViewState information is nothing but the data-posted back by the server to the client browser (Shown in Yellow). We call this as Round-Trip which is nothing but data flow from Client => Server => Client. The picture shows this as Round-Trip 01. Once Round-Trip is over Web Server remembers nothing about Post 01.
6.2.2 PostBack Round-Trip 2 (The Magic of ViewState)
Now, the user at Client Browser, Fills the Form field data and clicks the Add button. This starts the second HTTP Post which shown as Post 02 in the picture. This time, the Web Server receives the Data Filled by the user and Hidden Form Field data packed by it as part of previous Post-Back. We can refer Post-Back 01 in the picture.
Once the data received by the server, Event Handler can see the previous PostBack content of the lblListOfProducts. Because of this, string concatenation goes well in the Event Handler. After forming lblListOfProducts’ text, just like previous post back, the Server re-forms the View State information (With PostBack 02 information as it is required if Post 03 in-bounds) and performs the Post-Back 02. Now in the Client Browser we can see both the products in the check-out list.
Here, we studied the role of Page Level ViewState in Asp.Net pages when there are multiple Post-Back actions. We saw that how we failed when we want to build List of products in the Asp.Net Label Control. Then, we turned ON the EnableViewState property of the ASP.NET to fix that. This helps us in understanding the role of ViewState. One can put a break-point in the event handler and further dig in.
Listing 1: ViewState Example – Aspx Page
<%@ Page Language="C#"
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtml" >
<form id="form1" runat="server"
<asp:Label ID="Label1" runat="server"
Text="Product Name :" Width="107px"
style="z-index: 100; left: 10px;
position: absolute; top: 15px"
<asp:Label ID="Label2" runat="server"
position: absolute; top: 41px"
Text="Quantity :" Width="62px">
Style="z-index: 103; left: 122px;
<asp:Label ID="Label3" runat="server"
Text="List Of Products Ready for
Style="z-index: 105; left: 9px;
position: absolute; top: 120px"
<asp:Button ID="btnAdd" runat="server"
position: absolute; top: 38px"
Listing 2 – C# Code behind for EnableViewState Example
public partial class _Default :
protected void Page_Load(object sender, EventArgs e)
protected void btnAdd_Click(object sender, EventArgs e)
lblListOfProducts.Text = lblListOfProducts.Text +
txtProduct.Text + "-" +
txtQuantity.Text + "</br>";