質問

I have composite web server control, which at the moment doesn't perform any actions. My aim is to place inside it child controls beginning with checkbox. I try to do it in the following way:

[DefaultProperty("Text")]
[ToolboxData("<{0}:SubmitImageControl runat=\"server\"></{0}:SubmitImageControl>")]
public class SubmitImageControl : CompositeControl
{
    private CheckBox _checkBox;

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
    }

    protected override void CreateChildControls()
    {
        _checkBox = new CheckBox();
        Controls.Add(_checkBox);
        base.CreateChildControls();
    }
    protected override void RenderContents(HtmlTextWriter output)
    {
        _checkBox.RenderControl(output);
    }
}

Registering and placing on the page:

<%@ Register TagPrefix="uc" Namespace="PostBackHandlerApp.Controls" Assembly="PostBackHandlerApp" %>
<uc:SubmitImageControl runat="server" />

Checkbox appears on the page and everything seems fine until we look at the view state. Its value is

/wEPDwULLTExMTg2MzM0NjJkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBR1jdGwwMCRNYWluQ29udGVudCRjdGwwMCRjdGwwMD+PWeqrbtVyQSNMxvfjcmJkKAwpIuEPWJd+m5W6eJtQ

Then, if we simply remove the code Controls.Add(_checkBox);, view state size reduces greatly:

/wEPDwULLTExMTg2MzM0NjJkZLrri0oSGPS9ZiOTsRtSageoskXzCME4KCdRZxOiJyR9

If I move the code of child initialization and adding to OnInit method of my control (where, as far as I know, view state tracing is still disabled), result stays the same. Also, this MSDN article recommends to perform initialization only in CreateChildControls method:

You should create the child controls in the CreateChildControls method and not in OnInit or another life cycle phase. The server control architecture relies on calls to CreateChildControls whenever the Controls collection is needed, such as during data binding (if applicable).

Could anyone explain me why view state becomes larger? Thanks in advance.

役に立ちましたか?

解決 2

The reason why viewstate is populated is implementing IPostBackDataHandler interface by large part of data controls, including checkbox. Interface's method LoadPostData is called automatically after the LoadViewState event and viewstate gets populated from the posted data. Here is nice article about it.

他のヒント

Have you tried disabling viewstate for the checkbox in the control. I preusme the viewstate has to account for this control unless you specify otherwise? If you want to easily use this control within the lifecycle though you would want to leave the viewstate enabled.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top