从代码后面访问 asp:content
好吧,我是一名经验丰富的 Web 开发人员,但有时 ASP.Net 会欺骗我。 我在 asp.net 中有一个母版页。然后我有一个基于该母版页(home.aspx)的页面。现在在 home.aspx.cs 中,我想访问 asp:content 控件以通过编程方式添加控件。
Aspx 看起来像这样:
<asp:Content ID="leftCol" ContentPlaceHolderID="cphLeftCol" Runat="Server">
<asp:PlaceHolder ID="phLeftCol" runat="server">
</asp:PlaceHolder>
</asp:Content>
我希望我可以从后面的代码中引用“leftCol”。但那里却无人知晓。 为了进行测试,我添加了自己的占位符“phLeftCol”。我可以毫无问题地参考它。
有什么我没看到的吗?
Ok, I am an experienced web developer but sometimes ASP.Net is tricking me.
I have a master page in asp.net. Then I have a page based on that master page (home.aspx). Now in home.aspx.cs I want to access the asp:content controls to add controls programmatically.
Aspx looks like this:
<asp:Content ID="leftCol" ContentPlaceHolderID="cphLeftCol" Runat="Server">
<asp:PlaceHolder ID="phLeftCol" runat="server">
</asp:PlaceHolder>
</asp:Content>
I would expect that I can reference "leftCol" from my code behind. But it's unknown there.
For testing I added my own placeholder "phLeftCol". I can reference that without issues.
Is there something I don't see?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法直接从后面的代码访问 asp:Content 控件。内容控件不会在运行时添加到控件层次结构中,因此无法从后面的代码访问它以在运行时添加控件。要在运行时向其添加控件,您需要向内容控件添加另一个容器控件,并向其中添加控件(就像对占位符控件所做的那样)。
有关详细信息,请参阅这篇 MSDN 文章。
You can't access the asp:Content control directly from your code behind. A content control is not added to the control heirarchy at runtime so it is not accessible from the code behind to add controls to at runtime. To add controls to it at runtime, you need to add another container control to the content control and add the controls to that (as you did with the placeholder control).
See this MSDN article for more information.
您无法从主页代码隐藏中访问“leftCol”控件,因为它是该页面内容的持有者,并且您的主页代码在注入时不知道他的内容...您只能访问该控件中的控件内容。内容注入是从下往上进入 asp.net 的,因此主页的内容,在本例中是标签
之间的所有内容。和
,位于母版页的 placeHolder 中...干杯
You can't access "leftCol" control from home page code-behind because it is holder for content of that page, and code your home page is unaware of his content in the moment of injecting... you can only access controls in that content. Content injecting goes in asp.net from bottom up, so content of your home page, in this case everything between tags
<asp:Content ID="leftCol" ...> and </asp:Content>
, goes in placeHolder of a Master Page...cheers