ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

ASP.Net ViewState Example

Updated on August 8, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like playing video games & reading books.

1. Introduction to Page-Level ViewState

In ASP.Net, "Page-Level ViewState" plays an important role when page “post-back” happens for multiple times (More than one time). When data filled in a Web Form go to the server and returns back to the same browser session, we can call that as “Post-Back”. In this example, we are going to experiment how web server preserves the form data and learn the ViewState form-level property.

2. About the Example

Now look at the example below:

About  ViewState Example Form Design
About ViewState Example Form Design | Source

2.1 How User Interacts?

Here, the user will input the data in the “Product Name” and “Quantity” text boxes. When the user clicks the Add button, the data is posted to the server and server sends back the response to the same page. The Label at the bottom of the page is populated by the server before sending the response (Post-Back) back to the browser session.

2.2 Expected Behavior From User Point of View

The goal is to list the Products and Quantity given by the User. For example, let us say the user enters First Product along with Quantity and hits the Add button. He adds 2 more products like this and we are going to list all three products in the Label. This will make us understand the Following:

  1. What is the role of ViewState in PostBack?
  2. How form level data is preserved and what is a hidden field?

3. Creating the Form

To proceed with the example, create an "ASP.Net Website" project. Follow the steps below:

  1. Open Visual Studio (We Used 2005) and Navigate File->New->web site
  2. Select “Asp.Net WebSite” From the Template. Make sure Language is “Visual C#”, Then Click OK
  3. Rename the File Default.Aspx to ViewStateTracking.Aspx
  4. Design the Form in ViewStateTracking.Aspx page as per the Previous section.

The Control and its names are shown in the below Table:

Properties Of The Controls

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
lblListOfProducts, Label
Text=
txtProduct, TextBox
Text=
txtQuantity, TextBox
Text=
btnAdd, Button
Text=

Once the Form is Designed, Introduce the Property called “enableviewstate” and set its property value to “false”. Below is the Screenshot for the Steps:

Setting EnableViewState To False
Setting EnableViewState To False | Source

4. Add Button Event Handler

Let us add the Click event handler for the Add Button. Double-click the Add button from the Design Tab and it will Bring you to C# Code and edit the handler code as shown in the below code snippet:

Add Button Handler
Add Button Handler | Source

Code Explanation:

The handler code concatenates the Product (Marked as 2) and its Quantity (Marked as 3) from the corresponding TextBoxes 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 different line. Compile and build the code and then view the page in a browser (Right Click the Page and choose “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.

ViewState is set False, 3 Post-Back And its Result (Enlarge for More Detail)
ViewState is set False, 3 Post-Back And its Result (Enlarge for More Detail) | Source

5.1 First Data Post to Server

In the test, we are performing three

"Data Post-back"

. After filling the form field data (Product and Quantity), we hit the “Add” button and data is posted to the Server. We call this as First Post-back (In the depiction below, it is shown as Data Post 01).

5.2 Server Posting-Back the Page to Browser

5.2.1 Defaults Applied First

Once the server receives the posted data, it first applies the default values for the controls. Note that the defaults are taken from

“Form Design Defaults”,

which is given in Section 3 of this Article (For Example, Default for Label1 is “Product Name:” and Default for lblListOfProducts is <blank>).

5.2.2 Posted Data & Server Events

After Applying the defaults, Server overrides the defaults with the data received from the client browser. After that, it fires and handles the event triggers. 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 for Product Name and Quantity. The handler performs string concatenation and post-backs the data back to the browser. The Browser renders the lblListOfProduct with “Product No 1232-15” along with other Form Field Data which is not changed on the server.

5.3 Second Data Post & Importance of ViewState

5.3.1 Second Data Post to Server

As part of Data Post 02, we are entering Product Name as Product No 3215 and Quantity as 22 and Hit the Add button. We are doing this in the same browser session after postback happened. The Form Field Data filled by the user is posted to the server. Does Data Post 02 posts the Label Content “Product No 1232-15” to Server?

5.3.2 Previous post value? I don't Remember that - Server Says

The answer is No as it is not filled by the User and moreover it is rendered by the Server which is part of Previous Post-back. Now, when data received by the Server (Altogether a new post), it doesn’t remember the Label Text from the previous Post (Data Post 01) and thereby 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 thereby showing check-out list for the User.

OK. Now it is time to know the behavior of

EnableViewState = True

.

6. Page Behavior - "EnableViewState" Turned ON

In the previous section, we saw the need for ViewState by consecutively posting the Data to the Web Server. Now turn ON the ViewState property by setting the “EnableViewState” to True. Refer the picture in Section 3.

Now, look at the Picture below.

Asp.Net Post-Back behavior with ViewState turned ON
Asp.Net Post-Back behavior with ViewState turned ON | Source

6.1 HTTP GET

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 as we are requesting the web page from the server. This action is initiated by the client browser which is requesting the page from the Web Server.

6.2 Role Of ViewState Between HTTP POSTs

6.2.1 First Post-Back

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. In the Picture, it is shown as Post-Back 01. Here, view state 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. In the Picture, it is Marked as Round-Trip 01. Once Round-Trip is over Web Server doesn’t remember anything about Post 01.

6.2.2 Second Post-Back (The Magic of ViewState)

Now, the user at Client Browser, Fills the Form field data and clicks the Add button, this initiates the second Http Post which shown as Post 02 in the picture. This time, the Web Server receives the Data Filled by the user as well as Hidden Form Field data packed by the Server as part of previous Post-Back (In our Example it is Post-Back 01).

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 Client Browser that is we can see both the products in the check-out list.

Listing 1: ViewState Example - Aspx Page

<%@ Page Language="C#" 
AutoEventWireup="true"  
CodeFile="ViewStateTracking.aspx.cs" 
Inherits="_Default" %>

<!DOCTYPE html 
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server" 
        enableviewstate="true">
        <asp:Label ID="Label1" runat="server" 
        Text="Product Name :" Width="107px" 
        style="z-index: 100; left: 10px; 
            position: absolute; top: 15px" 
        Font-Names="Verdana" 
        Font-Size="Small">
        </asp:Label>
        
        <asp:TextBox ID="txtProduct" 
                runat="server" 
                Style="z-index: 101; 
                left: 122px; 
                position: absolute;
            top: 12px">
        </asp:TextBox>
        <br />
        
        <asp:Label ID="Label2" runat="server" 
        Font-Names="Verdana" 
        Font-Size="Small" 
        Style="z-index: 102;
            left: 45px; 
            position: absolute; top: 41px" 
            Text="Quantity :" Width="62px">
        </asp:Label>
        
        <asp:TextBox ID="txtQuantity" 
        runat="server" 
        Style="z-index: 103; left: 122px; 
        position: absolute;
        top: 38px"></asp:TextBox>
        
        <asp:Label ID="Label3" runat="server" 
        Font-Names="Verdana" 
        Font-Size="Large" 
        ForeColor="#FF8080"
        Height="26px" 
        Style="z-index: 104; 
        left: 7px; 
        position: absolute; 
        top: 86px"
        Text="List Of Products Ready for 
        Check-Out" Width="453px">
        </asp:Label>
        
        <asp:Label ID="lblListOfProducts" 
        runat="server" 
        Font-Names="Verdana" 
        Font-Size="Medium" 
        Height="227px"
        Style="z-index: 105; left: 9px; 
        position: absolute; top: 120px"
        Width="263px">
        </asp:Label>
        
        <asp:Button ID="btnAdd" runat="server" 
        OnClick="btnAdd_Click" 
        Style="z-index: 107;
            left: 288px; 
            position: absolute; top: 38px" 
        Text="Add" />
    </form>
</body>
</html>

Listing 2 - C# Code behind

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : 
    System.Web.UI.Page 
{
    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>";  
    }
}

Hope this Article explained the role of ViewState between Page Posts and PostBacks. Thank You.

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)