3

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.

2 Answers 2

7

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

2 Comments

This seems super weird to me but I have to say, I'm kind of in love with it. Never heard of it, but just happens to be exactly what I need right now.
One tip for anyone using this approach in a library - ParseControl will fail unless you provide a value for the AppRelativeVirtualPath attribute on the Page object. For example in VB: Dim pg As New Web.UI.Page pg.AppRelativeVirtualPath = "~\\"
0

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?

1 Comment

The code I have to use (and unfortunately cannot modify) is meant to populate a PlaceHolder with some HTMLControl objects and later on it inspects these elements and does some stuff based on that. Unfortunately I only have the raw HTML contents of the PlaceHolder so I need to recreate it.

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.