I am using viewstate quite a lot to store some flags and small data that needs to be persisted over the postbacks. Most of the time I use it like so
public partial class testPage : System.Web.UI.Page
{
public string item1 { get { return (string)(ViewState["item1"] ?? default(string)); } set { ViewState["item1"] = value; } }
public string item2 { get { return (string)(ViewState["item2"] ?? default(string)); } set { ViewState["item2"] = value; } }
public string item3 { get { return (string)(ViewState["item3"] ?? default(string)); } set { ViewState["item3"] = value; } }
public bool flag1 { get { return (bool)(ViewState["flag1"] ?? default(bool)); } set { ViewState["flag1"] = value; } }
public bool flag2 { get { return (bool)(ViewState["flag2"] ?? default(bool)); } set { ViewState["flag2"] = value; } }
protected void Page_Load(object sender, EventArgs e)
{
// flag1...
}
}
This is fine but looks a bit heavy and I'm not sure whether the desirialization process takes place only once or each time I access the variable. So I thought may be this technique is a bit better in terms of performance and management
public partial class testPage : System.Web.UI.Page
{
public PageVeriables Variables { get { return (PageVeriables)(ViewState["Variables"] ?? default(PageVeriables)); } set { ViewState["Variables"] = value; } }
protected void Page_Load(object sender, EventArgs e)
{
//Variables.flag1..
}
}
[Serializable]
public class PageVeriables
{
public string item1 { get; set; }
public string item2 { get; set; }
public string item3 { get; set; }
public bool flag1 { get; set; }
public bool flag2 { get; set; }
}
Question is does one really have any benefit over the other?
I would recommend doing the first example, even though it might be more typing.
It has two distinct advantages:
The first being what Michael Liu stated, which is that the size of the ViewState is has more granularity. If you only use 2 of 10 properties, then your ViewState size only accounts for the 2 that you've actually assigned to.
The second which I feel like even more important is that this follows the same pattern of UserControls, in that they have properties that you assign to. For example, given a UserControl with a Text
property, using the user control in the ASPX would look like the following:
<demo:MyUserControl Text="Some Text" runat="server" />
Which will also work in the designer. So there's something to be said for following convention, that (for the most part) properties get persisted between post-backs.