在回发后在PlaceHolder中保持动态添加的控件

时间:2014-01-24 10:14:36

标签: c# asp.net placeholder

在我的asp.net页面中,我放置了PlaceHolder控件,在单击按钮后,用户可以放置一些东西(例如:另一个控件)。但是回发之后PlaceHolder又空了。是否可以在PlaceHolder中维护所有程序化添加的控件并仅在用户不这样做时清除它?

<div>
    <asp:PlaceHolder ID="PlaceHolder1" runat="server" EnableViewState="true" ></asp:PlaceHolder>
</div>

<div>
    <asp:Button ID="Button1" runat="server" Text="addcontent" onclick="Button1_Click" />
</div>
<div>
    <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="postback" />
</div>

代码隐藏

       protected void Button1_Click(object sender, EventArgs e)
    {
        Image newImage = new Image();
        newImage.ImageUrl = "~/bear.jpg";
        PlaceHolder1.Controls.Add(newImage);            
    }

我想避免重写SaveViewState和LoadViewState。

1 个答案:

答案 0 :(得分:0)

使用<asp:UpdatePanel />

<asp:ScriptManager ID="scrpManager" runat="server" />
        <asp:UpdatePanel runat="server" ID="myUpdtPanel">   
            <ContentTemplate>
                <div>
                    <asp:PlaceHolder ID="PlaceHolder1" runat="server" EnableViewState="true" >

                    </asp:PlaceHolder>
                </div>

                <div>
                    <asp:Button ID="Button1" runat="server" Text="addcontent" onclick="Button1_Click" />
                </div>
                <div>
                    <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="postback" />
                </div>
            </ContentTemplate>         
        </asp:UpdatePanel>