views:

106

answers:

2

In a custom server control, I am simply writing out the number of child controls.

Is there a reason that the count would go to zero if <% %> tags are used within the body of the control tags?

Here's my extremely simplified control:

public class Script : Control
{
    public override void RenderControl(HtmlTextWriter writer)
    {            
        writer.Write(this.Controls.Count.ToString());
    }

}

When passed only Literal data, the count written is 1 as expected:

<my:Script runat="server" ID="script3" >
   function foo(){}
</my:Script>

When passed Literal data and some computed data, the count goes to zero:

<my:Script ID="Script1" runat="server" >
   function foot(){}
   <%=String.Empty %>
</my:Script>

There's nothing special about the String.Empty either. Anything I put here results in a count of zero.

Interestingly enough, other Control tags work fine however. The following counts 3:

<my:Script runat="server" ID="Script2">
   hi   
  <asp:HyperLink runat="server" NavigateUrl="/" Text="hi" />
</my:Script>

Is there another way to get the child "content" of the custom control? I would think there is some way, as does it, but I can only inspect the metadata for System.Web.UI.WebControls.Content - not the implementation.

+4  A: 

It's not possible to modify the Controls collection if your control has <%%> tags in the body (if you try to Add something, then you get an exception explaining just that). And for the same reason, the Controls collection is in fact empty. You can check if the collections is empty because of <%%> tags using the Controls.IsReadOnly property.

Pent Ploompuu
+1  A: 

Turns out the answer was much more simple than the approach I was taking in the first place. Simply call the overridden RenderControl method with your own HtmlTextWriter and then use the captured markup however you want.

var htmlString = new StringBuilder();
var mywriter = new HtmlTextWriter(new StringWriter(htmlString));
base.RenderControl(mywriter);

Now the rendered markup is available in htmlString, regardless of <% %> tags used in the control's body.

James Maroney