asp:label doesn't render children

。_饼干妹妹 提交于 2019-12-12 13:35:16

问题


I have an asp:label with a nested custom control and it simply doesn't render. I tried to register a custom WebControlAdapter for Label type and while debugging I noticed that there is apparently no control in the Controls collection, it seems to be completely ignoring any nested elements.

Here's markup

<asp:Label ID="lbl13" runat="server" AssociatedControlID="txt13" Text="<%$ Resources:Resources, lbl13 %>">
    <asp:ValidationMessage ID="vm13" runat="server" MessageFor="txt13" CssClass="field-validation-error"></asp:ValidationMessage>
</asp:Label>

Any idea how to bypass this problem?


回答1:


When you set the Text property, it clears the child controls. If you remove the Text="<%$ Resources:Resources, lbl13 %>" from the Label, your child controls should render.


EDIT
If you set the Text property to a static string and add only literal content, the label will only render the literal content:

<asp:Label runat="server" Text="Hello"> World</asp:Label>
Output: World

If you set the Text property to a static string and add child controls, the label will render the text and the child controls:

<asp:Label runat="server" Text="Hello">
   <asp:Label runat="server" Text="World" />
</asp:Label>
Output: HelloWorld

If you set the Text property using an expression builder, the label will only render the text:

<asp:Label runat="server" Text="<%$ Resources:Resources,Hello %>">
   <asp:Label runat="server" Text="World" />
</asp:Label>
Output: Localised version of "Hello"

To override this behaviour, you'll need a custom Label control. For example:

public class MyLabel : Label
{
   public override string Text
   {
      get { return base.Text; }
      set
      {
         if (HasControls())
         {
            Controls.AddAt(0, new LiteralControl(value));
         }
         else
         {
            base.Text = value;
         }
      }
   }
}


来源:https://stackoverflow.com/questions/16988845/asplabel-doesnt-render-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!