Custom Composite ASP.NET Control With No Parent Span...Simple

I’ve been watching the asp.net forums on the asp.net (www.asp.net) site lately. Some good questions. A number of not so good questions. Here was a good one.

Somebody asked how to create a custom server control that does not automatically render a span tag surrounding the contents. Good question. The guy who answered gave two choices, both good.

First, inherit from Control, not WebControl. That’s the easiest. Second, override the render, call the render on all the individual controls, and don’t call base.Render().

The first is much easier, unless you already have to do some of your own rendering anyway. If you do, just don’t call base.Render(). So, just as an example, here is the difference between rendering inheriting from Control and WebControl, respectively (both have three child controls, a button, a label, and a text box).


<input type="submit" name="myButton" value="Button" id="myButton" /><span id="myLabel">Label</span><input name="myTextBox" type="text" value="TextBox" id="myTextBox" />

or:


<span id="FancyWebControl1"><input type="submit" name="myButton" value="Button" id="myButton" /><span id="myLabel">Label</span><input name="myTextBox" type="text" value="TextBox" id="myTextBox" /></span>

As you can see the differences are all in the outer span, which includes the span tag itself and an id tag for the id given in the aspx page.

Here’s the page declaration, for your reference:


<Custom:FancyControl ID="FancyControl1" runat="server"></Custom:FancyControl>

<Custom:FancyWebControl ID="FancyWebControl1" runat="server" />

The first control, which descends from System.Web.UI.Control, only has its child controls rendered, so the id "FancyControl1" never gets rendered into the output.