ViewState not working across postbacks

I am trying to set a value into ViewState but the value isn't saving across postbacks. (I am actually trying to save a seriazable class, but for simplicity I am testing using a simple string value which isn't saving either).

I have tried manually setting the EnabledViewState = true property in the page directive of the master page, and I am also testing to see whether ViewState is enabled at the start of the method, which it is - but still the value is being reset on every postback.

The OnPreRender occurs late enough in the Page Lifecycle so that isn't the issue.  

Any ideas?

protected override void OnPreRender(EventArgs e)
    {
        bool viewState = this.IsViewStateEnabled;

        if (!Page.IsPostBack)
        {
            if (ViewState["Test"] == null)
                ViewState["Test"] = "This is a test";

            string test = (string)ViewState["Test"];
        }
    }

Open in new window

markerasmusAsked:
Who is Participating?
 
codingbeaverConnect With a Mentor Commented:
My guess is it has something to do with when you set ViesState value. The order of firing events is important.
0
 
SiyamalaConnect With a Mentor Commented:
try
change asp page - first line

AutoEventWireup="true" to false
0
 
markerasmusAuthor Commented:
Nope, that didn't work.
0
 
markerasmusAuthor Commented:
I've decided to use session state instead.
0
 
SiyamalaCommented:
Hi,

My answer answer has been accepted as a Assisted Solution ,But still the score Points is not Updated.

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.