user3770158
user3770158

Reputation: 389

Viewstate value erased when using Control

A little new to asp.net.

In my main.aspx page i have:

<users:UsersControl runat="server" ID="usersControl" />

In my UserControl page_load i have:

ViewState["test"] = "test";

In my Page_PreRender in main.aspx.cs:

log...(ViewState["test"]); <-- empty

Why dont i see the value on test?

Upvotes: 0

Views: 45

Answers (2)

James Simpson
James Simpson

Reputation: 1150

Im guessing here that the ViewState collection is different in the two contexts you have mentioned.

The first is in the context of the control, and the second is in the context of the page, therefore "test" key is not shared between them.

Also, it is not a good idea to expose a controls ViewState beyond the control boundary. For example use properties on the UserControl as the interface to the viewstate, e.g

public string Test
{
    get { return this.ViewState["Test"]; }
    set { this.ViewState["Test"] = value; }
}

ViewState should be considered an internal implementation detail of the user control.

Then whenever you need to use this property from the page:

this.userControl1.Test = "This Goes Into ViewState";

Upvotes: 1

Jabuciervo
Jabuciervo

Reputation: 86

I've found a similar answer to your question:

.net ViewState in page lifecycle

It's necessary to understand the life cycle, so why don't use Attributes on the UserControl?

Upvotes: 1

Related Questions