ViewState & PostBack

These samples demonstrate the ViewStateDictionary shim, IsPostBack, and AutoPostBack features. In Web Forms, these were core page lifecycle features. In BWFC, they work as migration compatibility shims — use them during migration, then graduate to native Blazor patterns.


1. Type-Safe ViewState (Interactive)

Use ViewState.Set<T>() and ViewState.GetValueOrDefault<T>() for type-safe access. In Interactive Server mode, ViewState is kept in memory — no serialization overhead.

Click count: 0

Code:

// Store with type safety
_counterPanel.ViewState.Set<int>("Count", _clickCount + 1);

// Retrieve with type safety — no casting needed
_clickCount = _counterPanel.ViewState.GetValueOrDefault<int>("Count");

2. IsPostBack Detection

IsPostBack is mode-adaptive: in SSR it checks HttpMethods.IsPost(), in Interactive mode it tracks whether OnInitialized has run before.

IsPostBack: False

Load count: 1

Code:

// In Web Forms:
if (!IsPostBack)
{
    BindGrid();  // Only on first load
}

// Same code works in BWFC — IsPostBack is false on first render,
// true on subsequent interactions

3. Graduating Off ViewState

ViewState is a migration shim, not a destination. Once your app runs in Blazor, refactor to native patterns — regular C# fields and properties.

During Migration (ViewState)

// Works, but indirect
ViewState.Set<string>("Filter", value);
var filter = ViewState.GetValueOrDefault<string>("Filter");

Native Blazor (Recommended)

// Direct, type-safe, no overhead
private string Filter { get; set; } = "";

// Or as a parameter:
[Parameter]
public string Filter { get; set; } = "";

Filter value (native property):