John Lechowicz
John Lechowicz

Reputation: 2583

How to get HTML of HtmlControl object in backend

I have a short snippet of C# code like this:

HtmlGenericControl titleH3 = new HtmlGenericControl("h3");
titleH3.Attributes.Add("class", "accordion");

HtmlAnchor titleAnchor = new HtmlAnchor();
titleAnchor.HRef = "#";
titleAnchor.InnerText = "Foo Bar";
titleH3.Controls.Add(titleAnchor);

What I want is a way to return a string that looks like this:

<h3 class="accordion"><a href="#">Foo Bar</a></h3>

Any thoughts or suggestions?

Upvotes: 2

Views: 1908

Answers (3)

Todd H.
Todd H.

Reputation: 2562

Here is an example that you can use to extend any HtmlControl to have a Render() method:

public static string Render(this HtmlAnchor TheAnchor)
{
    StringWriter sw = new StringWriter();
    HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
    TheAnchor.RenderControl(htmlWriter);
    return sw.ToString(); 
}

Upvotes: 1

wsanville
wsanville

Reputation: 37516

This is the method that I have used in the past to get a control's rendered HTML ahead of time (make sure to include System.IO):

protected string ControlToHtml(Control c)
{
    StringWriter sw = new StringWriter();
    HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
    c.RenderControl(htmlWriter);
    return sw.ToString();
}

Returns this for your test case:

<h3 class="accordion"><a href="#">Foo Bar</a></h3>

Upvotes: 4

Jeremy
Jeremy

Reputation: 4838

Shouldn't there be a Render method that forces it to emit its own HTML?

Upvotes: 0

Related Questions