State Management Part 1- View State

Name: *
My email: *
Recipient email: *
Message: *
Fields marked as bold are compulsory.
You haven't filled in compulsory values. The email is not correct

This article is about the various ways ASP .NET uses to handle state. Following a brief overview, we'll look through viewstate, one of the most common ways to store values within a page.

 

Getting Started

There are times we wish to store values we will use when a website visitor enters another page or triggers an event. For example, think of a customer buying stuff from an e-shop. The buyer will choose one product which we will have to remember until the check out. We do not wish to store this info in our database as we are yet to be sure that the customer will buy the product and pay for it. HTTP cannot help us, as it lacks the ability to store info. In other words it is a stateless protocol. It cannot store the state of the application, concerning a visitor, at a given moment.
 
In that case we turn to ASP .NET to help us. The framework offers various ways to store values. I'm sure you' ve heard most of them. The most popular are, view state, cookies, session, caching and application state. Using server's or client's resources is one way to create two basic categories. 
 

Various ways to store info

Most methods will use a dictionary to store their values. thus you can store a value in view state as ViewState["ProductID"] = 10; as well as Session["ProductID"] = 10;
 
Choosing the method to use, depends on what we want to do and the situation we are currently at.
 
We start our journey by examining view state.
 
 

What is View State?

View state is used extensively in web sites even when we are not aware of it. View state stores the values an asp control holds, in order to use them on postback. For example if we type "John" on a user name textbox, the value "John" will be brought back to the server using the view state. If view state did not exist (and we hadn't taken extra care about it) when we cliked save, the value "John" would be stored to our database but the page that the client would get, would show an empty textbox instead of appointing "John" as the user name. All such information will be posted back to the server stored in a hidden field called __VIEWSTATE. 
 
View state is unique for each web control within each page. Having two open tabs in our web browser, we will have two seperate view states. So if the first page states "John", this will not be mixed with the second page stating "George".
 
It seems we cannot use view state to carry values between pages as well. If we submit the value "John" in the user name textbox in the "Insert User Name" page and then redirect to the "Confirm User Name" page, that user name textbox will be empty.
 
 
View state is stored in the client. As a result it doesn't consume server's resources. However it takes up extra bandwith for the data to be transferred between the client and the server. If this is not taken into account we might end up increasing our response time.
 
 
 

Using the view state

Let's create a simple view state example. Within a web page we create two buttons and a label. 
 
    <asp:Button runat="server" ID="SaveTimeButton" OnClick="SaveTimeInViewstate" Text="Save Time"/>
    <br />
    <asp:Button runat="server" ID="LoadTimeButton" OnClick="LoadTimeFromViewstate" Text="Load Time"/>
    <br />
 
    Time in view state: <asp:Label runat="server" ID="TimeSavedLblID" />
 
The first button will save current time in view state while the second one will get the time saved with the first button and show it in the label. In case we hadn't pressed the first button we would get an error message stating the view state value we were looking for was empty.
 
 
    // Saves current time in view state state
    protected void SaveTimeInViewstate(object sender, System.EventArgs e)
    {
        ViewState["TimeSaved"] = DateTime.Now;
    }
 
ViewState element works like a dictionary. All we have to do is use a pair of name and value and use it like ViewState["Name"] = Value; . To use a ViewState value it's better to cast it to the expected type first.  The next method loads values from view state.
 
 
    //Loads time from view state
    protected void LoadTimeFromViewstate(object sender, System.EventArgs e)
    {
        if (ViewState["TimeSaved"] != null)
            //If the view state is not empty, show saved time.
            TimeSavedLblID.Text = ((DateTime)ViewState["TimeSaved"]).ToString("hh:mm:ss");
        else
            // else print error message
             TimeSavedLblID.Text = "<i>Sorry, no time stored in view state</i>";
    }
 
 
So, if we first press Save Time and then Load Time we store present time in ViewState["TimeSaved"] and the output will be 
 
Time in view state: 09:47:58
 
Of course the output will be different depending on when you pressed the Save button. If however we pressed Load without having pressed Save, then ViewState["TimeSaved"] would be null and the output would be 
 
Time in view state: Sorry, no time stored in view state 
 
If you are doing ok so far, you might have guessed that if you reload the page, view state will be empty, much like the first time you requested the page.
 
 

View state tips

Viewstate is automatically used in every control. If however you don't like or have no need for that you can use "EnableViewState = False" on a control to disable it.
 
View state is not encoded by default, as it was never meant to contain sensitive piece of information. This can make it easy to be accessed by a person who overhears the communication between the client and the server. If for any reason we want to avoid this, we can set the validation attribute in the machine.config file to 3DES and also set in ourPage EnableViewStateMAC="true".
 
 

Why View State?

Till now, we have only examined view state, so, it is hard to compare with other state management tools. However, we'll give it a try. We mentioned that view state is unique for every instance of a page. Other tools, like session and cookies cannot do that. Most likely new page values will replace the old ones (unless you use extra tricks). View state has no time expiration limits. It just waits, in your web browser's page. It's only gone when you close that tab. Even if you hit Back and Forward in your browser, it's still there. 
 
Every state management tool should be used when it's best suited to the situation. There is no ultimate solution when making choices like that. Picking view state may be a good thing in some cases but can be useless in others (eg when redirecting to some other page).
 
 

Conclusion

ASP.NET offers many ways to handle state, each one different  and suitable to the occasion needed. View state is one way, that is used automatically by ASP.NET to store values so that they show up again, when we postback a page. We can use view state ourselves to store values. It is important to remember that view state cannot be used between multiple pages or controls.

Back to BlogPreviousNext

Comments



    Leave a comment
    Name: