Often when I'm using the view state I'll have to code nice getters in my control or page to get me a value from the view state as the type I stored it in, for example:
public int PageCount
{
get
{
object viewStateObject = ViewState["PageCount"];
if (viewStateObject != null && viewStateObject is int)
{
return (int)viewStateObject;
}
return 0;
}
set
{
ViewState["PageCount"] = value;
}
}
As you can probably guess this gets pretty damn repetitive once you have more than one item to retrieve from view state.
So I decided to create a couple of nice extension methods to help with this, here's the code:
public static class StateBagExtensions
{
///
/// Gets an item from a state bag
///
/// The type of item to retrieve
///
"stateBag" />The state bag to retrieve the item from
///
"key" />The key of the item to retrive from the state bag
/// The item retrieved from the state bag or the default value
///
///
/// The default value is retrived using the default(T) call.
///
///
/// The default value is only returned if one of the following conditions is met:
///
/// The object for the given key does not exist in the state bag
/// The object for the given key retrieves a null value from the state bag
/// The object for the given key is not of the requested type
///
///
public static T GetOrDefault(this StateBag stateBag, string key)
{
return GetOrDefault(stateBag, key, default(T));
}
///
/// Gets an item from a state bag
///
/// The type of item to retrieve
///
"stateBag" />The state bag to retrieve the item from
///
"key" />The key of the item to retrive from the state bag
///
"defaultValue" />The
value to use
as the
default value /// The item retrieved from the state bag or the
default value ///
///
/// The
default value is only returned
if one of the following conditions
is met:
///
/// The
object for the given key does not exist
in the state bag
/// The
object for the given key retrieves a
null value from the state bag
/// The
object for the given key
is not of the requested type
///
///
public static T GetOrDefault(
this StateBag stateBag,
string key, T defaultValue)
{
object viewStateObject = stateBag[key];
if (viewStateObject !=
null && viewStateObject
is T)
{
return (T)viewStateObject;
}
return defaultValue;
}
}
Which means now my repetitive view state accessing properties now become:
public int PageCount
{
get
{
return ViewState.GetOrDefault("PageCount", 0);
}
set
{
ViewState["PageCount"] = value;
}
}
Which means accessing my viewstate is much simpler and also a hell of a lot DRYer.
Till next time :)