When building your own control ASP.NET, it is often useful to store some of the control's properties in ViewState. However, ViewState is not guantanteed to always be available; it can be turned off at the Page or Application level, thereby crippling your control. Microsoft recognized this with version 2.0 or ASP.NET and introduced the concept of ControlState.
For those of us not fortunate enough to be able to use ASP.NET 2.0 all the time, I came of with the following solution:
Build your code behind properties using the following example:
public class WeekNavigator : System.Web.UI.UserControl { protected System.Web.UI.HtmlControls.HtmlInputHidden ControlState;
...
public DateTime SelectedWeek { get { if( ControlState.Value.Length==0 ) return DateRangeStart( DateTime.Now ); else { byte[] utfBytes = Convert.FromBase64String(ControlState.Value); string uncodedState = System.Text.Encoding.UTF8.GetString(utfBytes); return DateRangeStart( DateTime.Parse(uncodedState) ); } } set { byte[] utfBytes = System.Text.Encoding.UTF8.GetBytes(value.ToString()); string base64 = Convert.ToBase64String(utfBytes); ControlState.Value = base64; } } ...
}
In the .ASCX file, add the following control:
<input type="hidden" id="ControlState" runat="server">
|