动态添加子控件的错误ClientID [英] Wrong ClientID for dynamically added child control
问题描述
我正在尝试将带有.ascx标记的asp.net用户控件重做为WebControl(仅.cs).
I am trying to rework asp.net usercontrol with .ascx markup to WebControl(only .cs).
在my_new_webcontrol.cs中,我有:
In my_new_webcontrol.cs I have:
private readonly DropDownList _source = new DropDownList();
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
_source.ID = String.Format("{0}{1}{2}", ID, IdSeparator, "Source");
Controls.Add(_source);
}
protected override void Render(HtmlTextWriter writer)
{
RenderContents(writer);
}
protected override void RenderContents(HtmlTextWriter writer)
{
_source.RenderControl(writer);
}
问题在于它使用id="MainContent_ComboBox1$Source"
和name="ctl00$MainContent$ComboBox1$Source"
生成DropDownList.生成的名称符合预期,但ID错误,此处应为 _ 而不是 $ .
Problem is that it generates DropDownList with id="MainContent_ComboBox1$Source"
and name="ctl00$MainContent$ComboBox1$Source"
. Name generated as expected but Id wrong and here should be _ instead of $.
如何实现id="MainContent_ComboBox1_Source"
和name="ctl00$MainContent$ComboBox1$Source"
.
更新1.
试图按照Knaģis的建议将DropDownList放入面板:
Tried to put DropDownList into Panel as Knaģis suggested:
private readonly DropDownList _source = new DropDownList();
private readonly Panel _panel = new Panel();
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
_panel.ID = ID;
_panel.Controls.Add(_source);
Controls.Add(_panel);
}
protected override void Render(HtmlTextWriter writer)
{
RenderContents(writer);
}
protected override void RenderContents(HtmlTextWriter writer)
{
_panel.RenderControl(writer);
}
没有成功.生成的HTML(ID和名称中缺少ComboBox1):
No success. Generated HTML(ComboBox1 in id and name missing):
<div id="MainContent_ComboBox1">
<select name="ctl00$MainContent$Source" onchange="javascript:setTimeout('__doPostBack(\'ctl00$MainContent$Source\',\'\')', 0)" id="MainContent_Source"></select>
</div>
答案
如Knaģis所述,我在服务器控件类声明中错过了INamingContainer
As Knaģis suggested I missed INamingContainer in my server control class declaration
public class ComboBox: WebControl, INamingContainer
推荐答案
您应该添加ID为ComboBox1
的子面板(或另一个容器控件),然后在其中添加ID为Source
的DropDownList
.让ASP.NET生成层次结构标识符.
You should add a child panel (or another container control) with ID of ComboBox1
and then within that add your DropDownList
with ID of Source
. Let the ASP.NET generate the hierarchical identifiers.
简而言之-如果要为重新设计的控件保留ClientID
和Name
的值,则应使用与.ascx
标记完全相同的控件树.
In short - if you want to preserve the values of ClientID
and Name
for your reworked control, you should use the exact same control tree as your .ascx
markup.
这篇关于动态添加子控件的错误ClientID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!