c# - 动态添加控件到控件列表

标签 c# .net asp.net .net-4.0

我有一个网页,用户需要在其中输入客户联系信息。他们可以输入 0 到无限数量的联系人。

我在页面上创建了这个页面代码:

<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
<asp:PlaceHolder ID="phCustomerContacts" runat="server" EnableViewState="true">/asp:PlaceHolder>
<asp:LinkButton ID="btnAddContact" runat="server" OnClick="btnAddContact_Click" CssClass="LinkButton" Text="Add Contact"/>

在我后面的代码中,我添加了这个:

   public void btnAddContact_Click(object sender, EventArgs e)
    {
        IList<CustomerContactProfile> customerContacts = new List<CustomerContactProfile>();
        if (ViewState["CustomerContactList"] != null)
            customerContacts = (List<CustomerContactProfile>)ViewState["CustomerContactList"];
        CustomerContactProfile contactProfile = (CustomerContactProfile)LoadControl("~/Controls/Embedded/CustomerContactProfile.ascx");
        customerContacts.Add(contactProfile);

        foreach (CustomerContactProfile contact in customerContacts)
            phCustomerContacts.Controls.Add(contact);

        ViewState["CustomerContactList"] = customerContacts;
    }

此代码不起作用,因为 ViewState 无法处理存储所有该控件数据。但是,我想不出另一种方法来存储已添加的控件。

asp:PlaceHolder 控件的 View 状态不保存任何内容,我需要保存控件,这样如果用户将一些数据放入第一个控件,数据不会保存当他们添加第二个时会丢失,依此类推。

最佳答案

与其存储整个控件,不如将底层数据存储在 session 中,并在每次重新加载页面时从该数据重建控件集。

关于c# - 动态添加控件到控件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4922051/

相关文章:

c# - 如何从 C# 执行 PowerShell 命令 `open-device`?

c# - 将 sqlite 用于 Windows Phone 8 应用程序

c# - 未执行 C# 中的垃圾收集。为什么?

asp.net - 如何使用 Identityserver4 请求刷新 token

c# - 使用谷歌翻译和我自己的翻译

c# - C# 和 SQL 新手 - 为什么我的 .AddWithValue 不起作用?

c# - 当我断开一个客户端套接字时 Windows 服务关闭

.net - 我们可以从Delphi 5应用程序调用.net(2.0) dll吗

.net - DataGridView 的 BindingList<T> 数据源

c# - 抛出异常 : The remote certificate is invalid according to the validation procedure