Lesson 20 - Maintaining State with ViewState

Tutorial Series: Free C# Fundamentals via ASP.NET Web Apps

Previous Article  |  Next Article


Get GitHub Code

In this lesson, we will cover an important ASP.NET concept, and that is managing state with ViewState. Consider how the Internet, or more specifically, the World Wide Web is intrinsically a stateless environment. This means that whenever you make a page request to a web server, it processes the request and sends the result as processed HTML. At which point, nothing is being held in memory on the server in question that points to your request instance, or the values that you’ve entered. Without using a framework, like ASP.NET or PHP, all of the information in the page and in its controls will be lost with each round-trip to the server.

To overcome this intrinsic limitation of web development, the ASP.NET page framework includes several different ways to maintain state across multiple PostBacks to the web server. ViewState is one such way that allows you to preserve variable and Control values between round trips to the web server.

Step 1: Create a New Project

To illustrate this, create a new ASP.NET project called “CS-ASP_020” and create the following Controls and programmatic IDs:

  1. valueTextBox

  2. Text1

  3. addButton

  4. resultLabel

cs-asp-020---maintaining-state-with-view-staet.001

Bear in mind that the user-input box for (2) is not a TextBox Server Control, but rather an HTML Input field fond in the Toolbox:

cs-asp-020---maintaining-state-with-view-staet.002

Step 2: HTML Fields Lose Information on PostBack by Default

Run the application and input some text for both input fields and then click “Add.” You will notice that only the Server Control input field will retain the value entered, whereas the HTML input field does not. The reason for this is because the Server Control, being an ASP.NET construct, attempts to produce the appearance of a consistently held state. It’s operating under the presumption that, despite the fact that HTML is stateless, many applications end up with some form of state-mimicking behavior (to make the user-experience more fluid, for example):

cs-asp-020---maintaining-state-with-view-staet.003

Step 3: ViewState Holds Values in an Encoded HTML String

ASP.NET is able to retain this information, between server requests, by storing it in a hidden HTML form field encoded with base64 encryption. You can see this by right-clicking in a blank area of the web page in the browser and selecting the browser option to “View Source” code:

cs-asp-020---maintaining-state-with-view-staet.004

Here we see this hidden information (hidden from view on the web page) that holds ViewState information, along with the encoded values. Notice how the encoded string looks like gibberish. That string holds all of the relevant values from the previous post made to the server by pressing the "Add" button. And when the user posts back to the server, this information will be silently posted back as hidden form input, creating a bridge that carries important data between page refreshes. The more information needing to be stored by the encoded string - the longer the string grows. This presents its own set of problems, which has led many developers to pursue ASP.NET MVC (Model-View Controller), rather than ASP.NET Web Forms. The solution that MVC provides probably won’t make much sense without first understanding the problems and solutions faced by using ViewState in ASP.NET Web Forms.

Tip:

The concept of something holding a state is common throughout programming. In broader terms, holding state can be thought of as a particular configuration of any given object (in the real world, or in code) at any given moment. Consider how a Rubik’s Cube changes state every time its puzzle pieces are shifted. You don’t throw out one Rubik’s Cube and get a new one whenever you want to change its state, however, this is kind of how ASP.NET/HTML works when it comes to creating the perception of holding state. The hidden information encoded in the HTML post back to the server is kind of like telling the server what the Rubik’s Cube’s previous state was and to create a new one that resembles that state.

Step 4: Storing ViewState Values in a Key/Value Pair

Now, let’s add values to the View State by writing the following code in Default.aspx.cs:

cs-asp-020---maintaining-state-with-view-staet.007

Here we are setting the ViewState property by accessing its Add() method. This method then takes in two strings, one representing the (1) “key” and the other representing the (2) value it refers to (this key/value pairing is called a “Dictionary” in programming terms). The ViewState property is being set on Page_Load and is retrievable whenever you click on the “Add” button by displaying the value referenced when accessing the ViewState’s particular (3) key.

cs-asp-020---maintaining-state-with-view-staet.008

Tip:

This Dictionary syntax might look a bit strange. Don’t worry too much about how it works right now. The important lesson here is demonstrating how the ViewState holds information in between posts to the server.

Now, let’s do something interesting:

  1. Initialize, at Page_Load, the ViewState[MyValue] key to hold an empty value.

  2. Once the button is clicked, create a temporary variable called value, that stores whatever ViewState[MyValue] currently holds.

  3. Take what’s currently stored in value and add to it what the user provided via valueTextBox, also adding a space after it.

  4. Replace whatever is currently in ViewState[MyValue] with whatever is assigned via value.

  5. After displaying through resultLabel, clear out what the user entered for valueTextBox.

cs-asp-020---maintaining-state-with-view-staet.010

Now, when running the application, enter into the Server Control TextBox the number 4 and click the button:

cs-asp-020---maintaining-state-with-view-staet.011

You will see the number displayed via the resultLabel:

cs-asp-020---maintaining-state-with-view-staet.012

Repeating this process, individually input each number in this sequence, clicking “Add” after each entry:

8, 15, 16, 23, 42

And you will see that the other entered values – previous to the last post back to the server - are retained in the ViewState[MyValue] property:

cs-asp-020---maintaining-state-with-view-staet.013

This example helps to illustrate the way that ViewState retains information between post backs to the server. While this concept isn't direcly C# related, it is important to touch on and it is helpful for us to maintain state between post backs in the future. Make sure you understand this concept before moving on. Great job so far!


Related Articles in this Tutorial:

Lesson 1 - Series Introduction

Lesson 2 - Installing Visual Studio 2015

Lesson 3 - Building Your First Web App

Lesson 4 - Understanding What You Just Did

Lesson 5 - Working with Projects in Visual Studio

Lesson 6 - Simple Web Page Formatting in Visual Studio

Challenge 1

Solution 1

Lesson 7 - Variables and Data Types

Lesson 8 - Data Type Conversion

Lesson 9 - Arithmetic Operators

Lesson 10 - C# Syntax Basics

Challenge 2 - ChallengeSimpleCalculator

Solution - ChallengeSimpleCalculator

Lesson 11 - Conditional If Statements

Lesson 12 - The Conditional Ternary Operator

Challenge 3 - ChallengeConditionalRadioButton

Solution - Challenge Conditional RadioButton

Lesson 13 - Comparison and Logical Operators

Lesson 13 Challenge - First Papa Bob's Website

Solution - Challenge First Papa Bob's Website

Lesson 14 - Working with Dates and Times

Lesson 15 - Working With Spans of Time

Lesson 16 - Working with the Calendar Server Control

Challenge 4 - Challenge Days Between Dates

Solution - Challenge Days Between Dates

Lesson 17 - Page_Load and Page.IsPostBack

Lesson 18 - Setting a Break Point and Debugging

Lesson 19 - Formatting Strings

Challenge 5 - Challenge Epic Spies Assignment

Solution - Challenge Epic Spies Assignment

Lesson 20 - Maintaining State with ViewState

Lesson 21 - Storing Values in Arrays

Lesson 22 - Understanding Multidimensional Arrays

Lesson 23 - Changing the Length of an Array

Challenge 6 - Challenge Epic Spies Asset Tracker

Solution - Challenge Epic Spies Asset Tracker

Lesson 24 - Understanding Variable Scope

Lesson 25 - Code Blocks and Nested If Statements

Lesson 26 - Looping with the For Iteration Statement

Challenge 7 - Challenge For Xmen Battle Count

Solution - Challenge For Xmen Battle Count

Lesson 27 - Looping with the while() & do...while() Iteration Statements

Lesson 28 - Creating and Calling Simple Helper Methods

Lesson 29 - Creating Methods with Input Parameters

Lesson 30 - Returning Values from Methods

Lesson 31 - Creating Overloaded Methods

Lesson 32 - Creating Optional Parameters

Lesson 33 - Creating Names Parameters

Lesson 34 - Creating Methods with Output Parameters

Challenge 8 - Challenge Postal Calculator Helper Methods

Solution - Challenge Postal Calculator Helper Methods

Mega Challenge Casino

Solution - Mega Challenge Casino

Lesson 35 - Manipulating Strings

Challenge 9 - Phun With Strings

Solution - Challenge Phun With Strings

Lesson 36 - Introduction to Classes and Objects

Challenge - Hero Monster Classes Part 1

Solution - Hero Monster Classes Part 1

Challenge - Hero Monster Classes Part 2

Solution - Challenge Hero Monster Classes Part 2

Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Lesson 38 - Understanding Object References and Object Lifetime

Lesson 39 - Understanding the .NET Framework and Compilation

Lesson 40 - Namespaces and Using Directives

Lesson 41 - Creating Class Libraries and Adding References to Assemblies

Lesson 42 - Accessibility Modifiers, Fields and Properties

Lesson 43 - Creating Constructor Methods

Lesson 44 - Naming Conventions for Identifiers

Lesson 45 - Static vs Instance Members

Challenge 10 - Challenge Simple Darts

Solution - Challenge Simple Darts

Lesson 46 - Working with the List Collection

Lesson 47 - Object Initializers

Lesson 48 - Collection Initializers

Lesson 49 - Working with the Dictionary Collection

Lesson 50 - Looping with the foreach Iteration Statement

Lesson 51 - Implicitly-Typed Variables with the var Keyword

Challenge 11 - Challenge Student Courses

Solution - Challenge Student Courses

Mega Challenge War

Solution - Mega Challenge War

Lesson 52 - Creating GUIDs

Lesson 53 - Working with Enumerations

Lesson 54 - Understanding the switch() Statement

Lesson 55 - First Pass at the Separation of Concerns Principle

Lesson 56 - Understanding Exception Handling

Lesson 57 - Understanding Global Exception Handling

Lesson 58 - Understanding Custom Exceptions

Lesson 59 - Creating a Database in Visual Studio

Lesson 60 - Creating an Entity Data Model

Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView

Lesson 62 - Implementing a Button Command in a GridView

Lesson 63 - Using a Tools-Centric Approach to Building a Database Application

Lesson 64 - Using a Maintenance-Driven Approach to Building a Database Application

Lesson 65 - Creating a New Instance of an Entity and Persisting it to the Database

Lesson 66 - Package Management with NuGet

Lesson 67 - NuGet No-Commit Workflow

Lesson 68 - Introduction the Twitter Bootstrap CSS Framework

Lesson 69 - Mapping Enum Types to Entity Properties in the Framework Designer

Lesson 70 - Deploying the App to Microsoft Azure Web Services Web Apps

Papa Bob's Mega Challenge

Papa Bob's Mega Solution Part 1 - Setting up the Solution

Papa Bob's Mega Solution Part 2 - Adding an Order to the Database

Papa Bob's Mega Solution Part 3 - Passing an Order from the Presentation Layer

Papa Bob's Mega Solution Part 4 - Creating the Order Form

Papa Bob's Mega Solution Part 5 - Adding Enums

Papa Bob's Mega Solution Part 6 - Creating an Order with Validation

Papa Bob's Mega Solution Part 7 - Calculating the Order Price

Papa Bob's Mega Solution Part 8 - Displaying the Price to the User

Papa Bob's Mega Solution Part 9 - Creating the Order Management Page


Comments

Please login or register to add a comment