ViewState Variable Reset After Postback

3.7k views Asked by At

I've seen this problem a lot, and it's usually because the ViewState variables are being evaluated too early in the page lifecycle, or that EnableViewState is false, but I've checked for both of these and they are as I'd expect them to be.

My code:

public Int32 MyNumber
{
    get
    {
        if (ViewState["MyNumber"] != null)
        {
            return (Int32)ViewState["MyNumber"];
        }

        return 0;
    }
    set
    {
        ViewState["MyNumber"] = value;
    }
}

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    if (!this.IsPostBack)
    {
        MyNumber = 23;
    }
}

protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);

    var numberValue = MyNumber;
}

When OnPreRender is first called, numberValue is 23. Every subsequent call thereafter it's 0. Every time there's a postback it appears to get reset.

Question

How do I get the value to persist after a postback?

What I've Tried

Bringing the value assignment outside of the check for a postback, but then that defeats the purpose of using ViewState in the first place.

2

There are 2 answers

0
Ahmed Elbatt On

actually you have a missing order in your code block excaution and that makes the value reset by zero everytime between post packs :) ... in the onload Method you wrote the base.onload() method before your code block and that lead the Viewstate to be reset to 0 .

Please fellow that code correction:

  public Int32 MyNumber
        {
            get
            {
                if (ViewState["MyNumber"] != null)
                {
                    return (Int32)ViewState["MyNumber"];
                }

                return 0;
            }
            set
            {
                ViewState["MyNumber"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(MyNumber.ToString()); // Result now is 23 :)
        }

        protected override void OnLoad(EventArgs e)
        {

            // I replaced the order of the code here to get the value of the Viewstate in MyNumber property ..
            if (!this.IsPostBack)
            {
                MyNumber = 23;
            }

            base.OnLoad(e);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            var numberValue = MyNumber;
        }

Good Luck :).

0
AudioBubble On

I was unaware there was also a ViewStateMode that would cause this behaviour if set to Disabled, which it was (on the master page).

I've now set that to Enabled on my control, and my ViewState values persist as I'd hope.