How do I get the HTML output of a UserControl in .NET (C#)?


Question

If I create a UserControl and add some objects to it, how can I grab the HTML it would render?

ex.

UserControl myControl = new UserControl();
myControl.Controls.Add(new TextBox());

// ...something happens

return strHTMLofControl;

I'd like to just convert a newly built UserControl to a string of HTML.

1
48
2/24/2019 7:49:45 AM

Accepted Answer

You can render the control using Control.RenderControl(HtmlTextWriter).

Feed StringWriter to the HtmlTextWriter.

Feed StringBuilder to the StringWriter.

Your generated string will be inside the StringBuilder object.

Here's a code example for this solution:

StringBuilder myStringBuilder = new StringBuilder();
TextWriter myTextWriter = new StringWriter(myStringBuilder);
HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter);
myControl.RenderControl(myWriter);
string html = myTextWriter.ToString();
57
4/20/2016 1:23:28 PM

//render control to string
StringBuilder b = new StringBuilder();
HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b));
this.LoadControl("~/path_to_control.ascx").RenderControl(h);
string controlAsString = b.ToString();

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon