ViewState Utility

In Web Forms, ViewState was a dictionary on every control that persisted values across postbacks. In this library, every component inheriting BaseWebFormsComponent exposes a ViewState property of type Dictionary<string, object> for migration compatibility. It is marked [Obsolete] — see Moving On below.


1. ViewState API — Add and Retrieve Values

Access ViewState on any component via a @ref reference. Use ViewState.Add("key", value) or ViewState["key"] = value to store values, and cast when retrieving.

Click count (stored in ViewState): 0

Code:

<Panel @ref="_panel">
    <p>Click count: @_viewStateClickCount</p>
    <button @onclick="IncrementViewState">Click Me</button>
</Panel>

@code {
    Panel _panel;
    int _viewStateClickCount = 0;

    void IncrementViewState()
    {
        // Store value in ViewState
#pragma warning disable CS0618
        _panel.ViewState["ClickCount"] = _viewStateClickCount + 1;

        // Retrieve value from ViewState
        _viewStateClickCount = (int)_panel.ViewState["ClickCount"];
#pragma warning restore CS0618
    }
}

2. ViewState with Multiple Keys

ViewState can hold multiple named values, just like Web Forms. Here we store a name and a color preference.

Stored — Name: (none), Color: (none)

Code:

#pragma warning disable CS0618
// Save
_settingsPanel.ViewState["UserName"] = _nameInput;
_settingsPanel.ViewState["FavColor"] = _colorInput;

// Load
_storedName = _settingsPanel.ViewState["UserName"] as string;
_storedColor = _settingsPanel.ViewState["FavColor"] as string;
#pragma warning restore CS0618

3. Moving On — Use C# Properties Instead

ViewState is marked [Obsolete]. In Blazor, component state is simply C# fields or properties — no dictionary indirection needed. This is type-safe, faster, and idiomatic Blazor.

Click count (C# field): 0

Code (the modern way):

@code {
    // Just use a C# field — no ViewState needed!
    private int _clickCount = 0;

    void IncrementProperty()
    {
        _clickCount++;
    }
}

Why migrate? C# fields and properties give you type safety at compile time, avoid casting from object, and are the standard Blazor pattern for component state.