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

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.


Solution 1:

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:

string html = String.Empty;
using (TextWriter myTextWriter = new StringWriter(new StringBuilder()))
{
    using (HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter))
    {
        myControl.RenderControl(myWriter);
        html = myTextWriter.ToString();
    }
}

Solution 2:

//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();

Solution 3:

UserControl uc = new UserControl();
MyCustomUserControl mu = (MyCustomUserControl)uc.LoadControl("~/Controls/MyCustomUserControl.ascx");

TextWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);

mu.RenderControl(hw);

return tw.ToString();