我有一个网页,用户需要在其中输入客户联系信息。他们可以输入 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/