开发者

ASP.NET Custom Server Control not persisting ViewState

开发者 https://www.devze.com 2022-12-14 09:10 出处:网络
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 s

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);
    }


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()

0

精彩评论

暂无评论...
验证码 换一张
取 消