Scott
Scott

Reputation: 1228

Dynamically generated HTML in C# to be formatted

I have an ASP.NET web forms site with a rather large menu. The HTML for the menu is dynamically generated via a method in the C# as a string. I.e., what is being returned is something like this:

<ul><li><a href='default.aspx?param=1&anotherparam=2'>LINK</a></li></ul>

Except it is a lot bigger, and the lists are nested up to 4 deep.

This is written to the page via a code block.

However, instead of returning a flat string from the method I would like to return it as formatted HTML, so when rendered it looks like this:

<ul>
    <li>
        <a href='default.aspx?param=1&anotherparam=2'>LINK</a>
    </li>
</ul>

I thought about loading the html into an XmlDocument but it doesn't like the & character found in the query strings (in the href attribute values).

The main reason for doing this is so I can more easily debug the generated HTML during development.

Anyone have any ideas?

Upvotes: 0

Views: 1127

Answers (4)

Dave Anderson
Dave Anderson

Reputation: 12294

I like to use format strings for this sort of thing, your HTML output would be generated with;

String.Format("<ul>{0}\t<li>{0}\t\t<a href='{2}'>{3}</a>{0}\t</li>{0}</ul>",
               System.Environment.NewLine,
               myHrefVariable,
               myLinkText);

Upvotes: 0

Phil Hunt
Phil Hunt

Reputation: 8521

Is there a reason you want to do this? This implicitly minified HTML will perform slightly better anyway. If you do still need to render the HTML for pretty display, you will either need to incorporate indentation into the logic that generates the output HTML or build your content using ASP.NET controls and then call Render().

Upvotes: 1

flq
flq

Reputation: 22849

Maybe you can work with an HtmlTextWriter? It has Indenting capabilities and it may actually be a cleaner thing as you could write straight into the output stream, which should be more "in the flow" than generating a string in memory etc.

Upvotes: 3

Oded
Oded

Reputation: 499002

Try loading the HTML into the HTML Agilty Pack. It is an HTML parser that can deal with HTML fragments (and will be fine with & in URLs).

I am not sure if it can output pretty printed (what you call "formatted") HTML, but that would be my first approach.

Upvotes: 0

Related Questions