ASP.NET ViewState Tips and Tricks #1

In User Controls or Custom Controls DO NOT use ViewState to store non public properties.

Persisting non public properties in ViewState results in loss of functionality if the Page hosting the controls has ViewState disabled since it can no longer reset values of non public properties on page load.

Example:

public class ExampleControl : WebControl
{
    private const string PublicViewStateKey = "Example_Public";
    private const string NonPublicViewStateKey = "Example_NonPublic";

    // DO
    public int Public
    {
        get
        {
            object o = this.ViewState[PublicViewStateKey];

            if (o == null)
                return default(int);

            return (int)o;
        }
        set { this.ViewState[PublicViewStateKey] = value; }
    }

    // DO NOT
    private int NonPublic
    {
        get
        {
            object o = this.ViewState[NonPublicViewStateKey];

            if (o == null)
                return default(int);

            return (int)o;
        }
        set { this.ViewState[NonPublicViewStateKey] = value; }
    }
}

// Page with ViewState disabled
public partial class ExamplePage : Page
{
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        this.Example.Public = 10; // Restore Public value
        this.Example.NonPublic = 20; // Compile Error!
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s