Saturday 12 February 2011

Asp.Net: Using ViewState to store data on the page.

Question:
How do I store data on a page during post-back round-trips?
How to use ViewState on pages?



Answer:
The page object has a ViewState property which gives access to a StateBag.
You can store here serializable data.
Data will be transformed into string and stored inside a hidden field with the id "__VIEWSTATE".
That means, that you should not put too much inside.

Here is an example that shows simple cases with null tests.
public String MyName
{
    get 
    { 
        object o = ViewState["keyForName"]; 
        return (o == null)? String.Empty : (string)o;
    }
    set
    {
        ViewState["keyForName"] = value;
    }
}

public int MyAge
{
    get
    {
        object o = ViewState["keyForAge"];
        return (o == null) ? 10 : (int)o;
    }
    set
    {
        ViewState["keyForAge"] = value;
    }
}

No comments: