Tamas Czinege
Tamas Czinege

Reputation: 121294

ASP.NET Parsing raw HTML into Controls

Is it possible in ASP.NET to take a string containing some HTML and make ASP.NET to parse it and create a Control for me? For example:

string rawHTML = "<table><td><td>Cell</td></tr></table>";
HTMLTable table = MagicClass.ParseTable(rawHTML);

I know that this is a bad thing to do but I am in the unfortunate situation that this is really the only way I can achieve what I need (as I cannot modify this particular coworker's code).

Also, I know that LiteralControl allows you to have a control with arbitrary HTML in it, but unfortunately I need to have them converted to proper control.

Unfortunately, HTMLTable does not support the InnerHTML property. I need to preserve the HTML tree exactly as it is, so I cannot put it into a <div> tag.

Thanks.

Upvotes: 3

Views: 6068

Answers (2)

Mark Brackett
Mark Brackett

Reputation: 85645

The closest I think you'll get is Page.ParseControl, which is the ASP.NET parser. The downside is that the text you have is a LiteralControl, since it doesn't have runat="server" on it - so you 'll do a very tiny bit of string manipulation beforehand.

In otherwords:

this.ParseControl("<table><tr><td>Cell</td></tr></table>")

will produce:

Control
 LiteralControl

whereas:

this.ParseControl("<table runat=\"server\"><tr><td>Cell</td></tr></table>")

will produce:

Control
 HtmlTable
  HtmlTableRow
   HtmlTableCell
    LiteralControl

Upvotes: 7

Stephen Wrighton
Stephen Wrighton

Reputation: 37819

You could traverse the HTML string a token at a time (token defined here as HTML Element or HTML InnerText), and determine which control needs to be instantiated, and what attributes it needs. But, that would be something highly... evil in the writing.

Why exactly do you need it to be a "proper" control as opposed to a text inside of a Literal control?

Upvotes: 0

Related Questions