I'm working on an Html Helper to create a control that will consist of multiple elements, build using TagBuilders. The control itself will be rendered using a TagBuilder that contains a div with all child elements.
I implemented a Render() method to create the control and return it as a string:
public class MyCustomControl
{
public override string ToString()
{
return Render();
}
private string Render()
{
TagBuilder mainContainer = new TagBuilder("div");
// Generate child elements and append to mainContainer...
using (StringWriter writer = new StringWriter())
{
mainContainer.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
}
And made an extension method to call it in a Razor View:
public static MyCustomControl(this IHtmlHelper html)
{
return new MyCustomControl();
}
And include it in Views like this:
@(Html.MyCustomControl()
)
The problem is instead of being rendered html, I get raw html text output to the View, so I actually see:
<div><!-- all child controls html here --></div>
Instead of there being an element there.
TagBuilder.WriteTorequires anHtmlEncoderandDefaultis the only implementation available.