我在ASP.NET 3.5中创建了LoginView ASP.NET控件的“克隆”,以满足我们公司的需求,并且我试图了解它是如何实现在不同模板中设置具有相同ID的控件的能力的。 例如,这是使用LoginView控件的ASPX标记:
<asp:LoginView ID="lv" runat="server">
<AnonymousTemplate>
<asp:Label ID="lbl" runat="server" />
</AnonymousTemplate>
<LoggedInTemplate>
<asp:Label ID="lbl" runat="server" />
</LoggedInTemplate>
</asp:LoginView>
这是有效的标记,页面工作正常 现在我创建了自定义控件:
[ParseChildren(true)]
[PersistChildren(false)]
public class ContentControl : Panel
{
[PersistenceMode(PersistenceMode.InnerProperty)]
public PlaceHolder AnonymousView { get; set; }
[PersistenceMode(PersistenceMode.InnerProperty)]
public PlaceHolder LoggedinView { get; set; }
public ContentControl()
{
this.Init += new EventHandler(ContentControl_Init);
}
void ContentControl_Init(object sender, EventArgs e)
{
if (AnonymousView == null)
{
AnonymousView = new PlaceHolder();
}
if (LoggedinView == null)
{
LoggedinView = new PlaceHolder();
}
this.Controls.Add(AnonymousView);
this.Controls.Add(LoggedinView);
AnonymousView.ID = "AnonymousView";
LoggedinView.ID = "LoggedinView";
AnonymousView.Visible = !MyContext.IsLogged;
LoggedinView.Visible = MyContext.IsLogged;
}
}
现在当我使用我的控件和以下标记时,我收到错误,即ID为“lbl”的控件在页面上存在多次:
<TL:ContentControl ID="c" runat="server" CssClass="dd">
<AnonymousView>
AnonymousView
<asp:Label ID="lbl" runat="server" />
</AnonymousView>
<LoggedinView>
LoggedinView
<asp:Label ID="lbl" runat="server" />
</LoggedinView>
</TL:ContentControl>
如何允许两个模板中具有相同ID的控件?
答案 0 :(得分:3)
您需要开发模板化控件:Building Templated Custom ASP.NET Server Controls
并使用实现INamingContainer的控件作为模板容器:Use TemplateInstance.Single to avoid FindControls