HowTo: Control the rendered Html tag on your custom, composite server controls

Normally when you want to achieve that your custom server control is rendered inside a specific HTML tag you don't override the Render method, but you do something like
public class MySrvControl : WebControl, INamingContainer
{
public MySrvControl() : base(HtmlTextWriterTag.Div)
{
...
}

...

}

Now most often you'll probably have a composite control, meaning that you are aggregating a couple of already existing controls inside your custom server control, providing some further functionality. In such a case, the .Net framework provides the CompositeControl class which should be inherited in that case:
public class MySrvControl : CompositeControl
{
public MySrvControl() : base(HtmlTextWriterTag.Div)
{
...
}

...

}
Note, you don't need the INamingContainer marker interface any more, because it's already done by the CompositeControl. The line "base(HtmlTextWriterTag.Div) however will give you a compiler error, since there is no constructor on the CompositeControl which is taking parameters. So to still provide the same rendering functionality, you simply add
public class MySrvControl : CompositeControl
{
public MySrvControl()
{
...
}

protected override HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Div;
}
}

...

}
Kindle

Comments

0

Your ad here?