在按钮单击时动态加载用户控件的问题

时间:2010-04-05 17:38:29

标签: c# asp.net user-controls

我有一个页面,我在其中动态加载用户控件,如下所示:

Default.aspx的:

    <cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </cc1:ToolkitScriptManager>

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

Default.aspx.cs:

    protected void Page_Load(object sender, EventArgs e)
    {
        var ctrl = LoadControl("~/UserCtrl1.ascx");
        ctrl.ID = "ucUserCtrl1";
        PlaceHolder1.Controls.Add(ctrl);
    }

以下是 UserCtrl1.ascx

的代码

<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Click" />
<br />
<asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder>

单击Button1时,我正在动态加载另一个用户控件

UserCtrl1.ascx.cs

    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "UserControl - 1 button clicked!";

        var ctrl = LoadControl("~/UserCtrl2.ascx");
        ctrl.ID = "ucUserCtrl2";
        PlaceHolder2.Controls.Add(ctrl);
    }

以下是UserCtrl2.ascx的标记

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:Label ID="Label2" runat="server"></asp:Label>
        <asp:Button ID="Button2" runat="server" Text="Button2" OnClick="Button2_Click" />
    </ContentTemplate>
</asp:UpdatePanel>

UserCtrl2.ascx.cs

    protected void Button2_Click(object sender, EventArgs e)
    {
        Label2.Text = "UserControl - 2 button clicked!";
    }

当我在UserCtrl1中单击Button1加载页面后,click事件将触发,我可以看到Label1文本。它也正确加载了UserCtrl2,但是当我点击UserCtrl2中的Button2时,点击事件就会触发,甚至更糟糕的是当我单击Button2两次时,UserCtrl2控件从页面中消失。我怎样才能解决这个问题?

1 个答案:

答案 0 :(得分:3)

第二个控件的问题在于,只有在点击按钮1后才会丢失它。但是当其他一些(不是按钮1点击)回发时,你的第二个控件没有加载。

其中一个可能的修复方法是保存一些标记(例如在ViewState中),它将帮助您确定是否应加载第二个控件(并在页面加载时加载)。

protected void Button1_Click(object sender, EventArgs e)
{
    Label1.Text = "UserControl - 1 button clicked!";

    var ctrl = LoadControl("~/UserCtrl2.ascx");
    ctrl.ID = "ucUserCtrl2";
    PlaceHolder2.Controls.Add(ctrl);

    this.SecondControlLoaded = true; // This flag saves to ViewState that your control was loaded.
}

protected void Page_Load(object sender, EventArgs e)
{
    var ctrl = LoadControl("~/UserCtrl1.ascx");
    ctrl.ID = "ucUserCtrl1";
    PlaceHolder1.Controls.Add(ctrl);

    if (this.SecondControlLoaded)
    {
        var ctrl = LoadControl("~/UserCtrl2.ascx");
        ctrl.ID = "ucUserCtrl2";
        PlaceHolder2.Controls.Add(ctrl);
    }
}