【问题标题】:How to add persistent dynamic controls based on user input (not on initial page load)如何根据用户输入添加持久动态控件(不是在初始页面加载时)
【发布时间】:2010-10-13 11:23:35
【问题描述】:

我熟悉在第一次加载页面和后续回发时创建和保留动态控件,但我在以下用户启动场景中遇到了问题。 .

在我的演示中,我有一个占位符、两个按钮和一个文字

<div>
    <asp:PlaceHolder ID="phResponses" runat="server" />
</div>
<div>
    <asp:Button ID="btnAdd" Text="Add" runat="server" OnClick="Add"/>
    <asp:Button ID="btnInspect" Text="Inspect" runat="server" OnClick="Inspect"/>
</div>
<div>
    <asp:Literal ID="litResult" runat="server"/>
</div>

我希望用户能够单击添加按钮以提供响应,所以我...

protected void Page_Init(object sender, EventArgs e)
{
    BuildControls();
}

protected void Add(object sender, EventArgs e)
{
    BuildControls();
}

protected void BuildControls()
{
    phResponses.Controls.Add(new LiteralControl { ID = "response_" + _Count.ToString() });
    _Count++;
}

_Count 是一个静态成员变量,使我能够为新控件拥有唯一的 ID。我意识到我需要重建 Page_Init 上的动态控件,但问题是每次回发时我都会得到 2 个新的 Literal 控件。此外,如果将任何 Text 属性放入新控件中,则在重建控件时它会丢失。

那么如何避免添加多个控件,以及如何在重建这些控件时保留新添加的属性?

我使用以下方法检查响应

protected void Inspect(object sender, EventArgs e)
{
    foreach (var control in phResponses.Controls)
    {
        if (control is LiteralControl)
        {
            litResults.Text += "<p>" + control.Text + " : " + control.ID + "</p>";
        }
    }
}

由于 Page_Init 上的重建,它本身添加了另一个不需要的控件

【问题讨论】:

    标签: asp.net page-lifecycle dynamic-controls


    【解决方案1】:

    我不确定我是否完全理解您的要求,但您似乎只想确保每个生命周期只调用一次 BuildControls。您可以通过以下更改来做到这一点:

    1. 添加一个新的private bool _isControlsBuilt = false;
    2. 在调用BuildControls之前将Page_Init更改为检查_isControlsBuilt
    3. BuildControls 内将_isControlsBuilt 设置为true
    4. 确保BuildControls 出现在page lifecycle 中早于Page_Init

    至于在回发时丢失控件的值,那就是它们永远不会触及视图状态。我不确定它是否有效,但我的第一个猜测是在BuildControls 的末尾添加一行以调用Page.RegisterRequiresControlState

    protected void BuildControls()
    {
        LiteralControl newLiteral = new LiteralControl { ID = "response_" + _Count };
        this.RegisterRequiresControlState(newLiteral);
        phResponses.Controls.Add(newLiteral);
    
        _Count++;
        _isControlsBuilt = true;
    }
    

    如果这不起作用(这可能意味着这里对您重要的是_view_state,而不是_control_state),您可能需要考虑滚动您自己的视图状态。我在my answer to #3854193 中写过如何做到这一点,您可能会觉得这很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-01
      • 1970-01-01
      相关资源
      最近更新 更多