ASP.NET ViewState Tips and Tricks #1
- by João Angelo
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!
}
}