2

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?

3 Answers 3

4

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

...or extend all HTMLControls at once by changing HtmlAnchor to HtmlControl in the above code. ;-)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.