views:

231

answers:

1

Hello, I have created a custom Server control that processes some data, stores that data to ViewState, and then renders itself from that data. I am using the debugger and can physically see the data getting set to ViewState:

public string RawData
    {
        get
        {
            string result = null;

            if (ViewState["RawData"] != null)
            {
                result = ViewState["RawData"].ToString();
            }

            return result;                
        }
        set
        {
            ViewState["RawData"] = value;
        }
    }

However, after postback the ViewState value is not persisted, and it is null. Why is this happening? Where can I look to try to troubleshoot? I can tell that the ViewState hidden field length has increased since using this approach.

Thanks in advance!

EDIT: Here is my Render method to see where I am setting the ViewState:

    protected override void Render(HtmlTextWriter writer)
    {
        if (this.RawData == null)
        {
            StringBuilder content = new StringBuilder();

            content.Append(this.BuildHeader());
            content.Append(this.BuildLevelsMarkup());
            content.Append(this.BuildFooter());

            this.RawData = content.ToString();
        }

        writer.Write(this.RawData);
    }
+4  A: 

One possible source of error would be if you are setting Viewstate Values during the OnInit event. ViewState is only stored after "TrackViewState" is called. http://msdn.microsoft.com/en-us/library/ms972976.aspx

Maybe you are "to early". Or "too late" if you set your Data during Render.

EDIT: Your are changing your value during "Render" - that's too late! During Render the ViewState is already written to the HTML Stream. Try to move your code to OnPreRender()

Arthur
I am loading my data on Page_Load. I included more code in the original post so you can see when I set my data.
Mike C.
Your code indicates you are doing it in Render, which as Arthur correctly states is too late.
Dan Diplo
Thanks for the edit... I overlooked that fact. OnPreRender() worked great!
Mike C.