带有内容模板的ASP.NET自定义控件
作者:互联网
我为公司的需要在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的控件?
解决方法:
您需要开发模板控件:Building Templated Custom ASP.NET Server Controls
并使用实现INamingContainer的控件作为模板容器:Use TemplateInstance.Single to avoid FindControls
标签:custom-controls,user-controls,asp-net,c 来源: https://codeday.me/bug/20191127/2075332.html