Saturday, February 19, 2011

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.

Answered (below):

Using azamsharp's method worked - here's the code example:

TextWriter myTextWriter = new StringWriter();
HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter);

myControl.RenderControl(myWriter);

return myTextWriter.ToString();

You'll need to be using System.IO (to get the StringWriter class).

From stackoverflow
  • Call it's .RenderControl() method.

  • 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.

    korchev : you could also add the control in a "live" controls collection to avoid random exceptions.
  • override the REnderControl method

    protected override void Render(HtmlTextWriter output)
    {       
       output.Write("<br>Message from Control : " + Message);       
       output.Write("Showing Custom controls created in reverse" +
                                                        "order");         
       // Render Controls.
       RenderChildren(output);
    }
    

    This will give you access to the writer which the HTML will be written to.

    You may also want to look into the adaptive control architecture of asp.net adaptive control architecture of asp.net where you can 'shape' the default html output from controls.

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

0 comments:

Post a Comment