I was thinking about if a custom made ViewState variable is always available on each page visit (same browser session) (like Session but client-side) or only at a page postback? I know this is client-side data that is always encapsulated with the Request packet and the Response packet from the server.
I was testing this right now, and I did the following:
on Home.aspx:
protected void Page_Load(object sender, EventArgs e)
{
ViewState["test"] = "test1";
}
protected void Button1_Click(object sender, EventArgs e)
{
string test = ViewState["test"].ToString();
Server.Transfer("Default.aspx");
}
And on Default.aspx:
protected void Page_Load(object sender, EventArgs e)
{
string test = ViewState["test"].ToString();
}
But I get NullReferenceException. So it means that ViewState["test"] doesn’t exists because the ViewState is completely new and regenerated. So my conclusion is that you can use ViewState variables only when doing a form postback (but in fact, you do always a redirect after a form postback, so I can’t use ViewState always…).
Am I right with my opinion?
ViewState can be configured in different ways, with different (or custom) providers, or can be completely disabled. However, the default provider is that it is a form-field, so yes: in that default configuration case it will only exist on a POST, and will not exist for a GET. A transfer operates essentially like a GET.
If you need data between unrelated pages, but user-related – use session-state, or something cookie-based.
In unrelated news: view-state is pretty horrible in many ways – think of the kittens!