ViewState

As the follow up to previous post, I’ll tell you about the improved version of ViewState in ASP.NET 2.0 today, ControlState. In fact, I never wrote a control that uses ControlState myself but I’ve read about it once. It takes a lot of effort compare to ViewState and I think it’s why there’re not many controls use it.

Using ViewState is as easy as pie. It’s only a indexed collection or you can call it Hash or Dictionary.  Throw any serializable object into the ViewState and it will be serialized, encoded and persisted to the web form. That’s all. You don’t have to register any index or anything. Look at this piece of code.

public int _currentIndex
public int CurrentIndex
{
    get
    {
        if (ViewState["CurrentIndex"] != null)
            _currentIndex = Convert.ToInt32(ViewState["CurrentIndex"]);
        }
        return _currentIndex;
    }
    set
    {
        ViewState["CurrentIndex"] = value;
        _currentIndex = value;
    }
}

In contrast to the ease of ViewState, ControlState introduces more overhead and have to be registerd before we can use it. You have to register your control in initialization event  and tell how to save and load state from the state object before use it.

Below is an example I copied from MSDN Library. I cut the ViewState section off to help you read it easier.

public class IndexButton : Button
{
    private int indexValue;

    [ Bindable(true),
    Category("Behavior"),
    DefaultValue(0),
    Description("The index stored in control state.") ]
    public int Index { 
        get { return indexValue; }
        set { indexValue = value; }
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        Page.RegisterRequiresControlState(this);

    }
    protected override object SaveControlState()
    {
        object obj = base.SaveControlState(); 
        if (indexValue != 0)
        {
            if (obj != null)
            {
                return new Pair(obj, indexValue);
            }
            else
            { return (indexValue); }
        }
        else
        { return obj; }
    }
    protected override void LoadControlState(object state)
    {
        if (state != null)
        {
            Pair p = state as Pair;
            if (p != null)
            {
                base.LoadControlState(p.First);
                indexValue = (int)p.Second;
            }
            else
            {
                if (state is int)
                {
                    indexValue = (int)state;
                }
                else
                {
                    base.LoadControlState(state);
                }
           }
        }
    }
}

Pair is a container class that contains 2 objects. The class that contains 3 object named Triplet. They’re mostly use in ViewState and ControlState state object. I don’t recommend to use them in other purposes or you’ll end up with confusion.

Despite of it overhead, ControlState has been widely use instead of ViewState. Because control state can’t be disabled; as a result, you can guarantee that turning off ViewState doesn’t make your control unworkable. GridView use ControlState over ViewState to store its various indices. I don’t know about the other but I assume that almost all new controls in ASP.NET 2.0 utilize ControlState as well.

Although it can’t be disable, this makes it a 2-edges sword. Remember again, ControlState is the ViewState that cannot be disabled. You have to decide wisely what will be kept in ControlState because your HTML can be bloated with a lot of ControlState data. Stay away from both ViewState and ControlState, if you can.

Technorati tags: , ,

ViewState again?

23 Sep 2007

Although I don’t like the ViewState, I have to confess that I used Viewstate to solve many problems while I code in ASP.NET. Today, I found some interesting pieces about good side of ViewState that I never thought of; using it in AJAX to build a history management tool.

ViewState is a concept that storing the state across request. The idea is miraculously easy; persists the user state in a hidden field and re-post it every time you make a request to server. Microsoft implemented ViewState to make a new  web application user interface technique and called it Web Form which is similar to its Windows Application counterpart, Windows Form.

With ViewState you can build a web application in the same way you do in WinForms. Most of ASP.NET Server Controls in ASP.NET 1.x utilize ViewState as their state storing mechanic. For example, DataGrid uses it to store Page index, Edit index and Select index, Button and Textbox use it to store style and text value, etc. It states and values will be saved across the requests and let you treat them like no request at all.

Even though ViewState brings us many benefits. It also has an important downside, the size of state persists in a page. As I mentioned before, almost every controls create their own Viewstate data. Imagine you have a web with 2 DataGrids. Each of them consists of a collection of DataRow which are represents through 5-6 label controls and 2 LinkButtons; these will generate couple long lines of Viewstate. This usually adds 5-10 KB to HTML size. I ever saw a page that its page size was nearly 100 KB and half of it came from ViewState. And this is a reason why I dislike WebForm. Despite of its usefulness, many ASP.NET gurus recommend to disable Viewstate when you don’t use it and save bandwidth in exchange of some less important functions. However, in ASP.NET 2.0 the viewstate had been developed to ControlState which you can’t disable anymore.

Before we continue to AJAX I have something to tell you about ViewState. Last month I read a .NET blog, I found a posts that is an interesting quote of ViewState.

Nikhil has some valid points in defence of webforms:

Sooner or later you are going to need some state that’s why we have viewstate :) and you will typically maintain your own state in a hidden field. Webforms is a framework and you roll your own specific framework for every new site.  There is nothing you can with MVC that you can’t do with webforms. 

Ivan Corto Parrero’s Blog

At first, I think it can’t be true and he is too confident in ViewState. Nowadays, MVC already proofed itself how it fit in the Web Framework. Look at those MVC framework out there; Ruby on Rails, django, Symphony and etc. We have a long tails convoy in MVC. ViewState and ASP.NET WebForm is out. Even ASP.NET Team is announced a new MVC Framework for ASP.NET. Anyway, I have to think it again after I read this post.

We approach this problem by storing state information in a hidden form field because the value of form fields persists across pages during the entire browser session. If we set the value of our form field to the current state of the application every time the application changes state, we can then initialize our page appropriately when the user returns to our application after having interacted with it beyond its initial state.

Yahoo User Interface Blog

I found this when I was searching for how to make a cross-browser history management tool. After I read this sentence I was too shock to read on.  ViewState again? It seems to be true.. sigh