开发者

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?


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.


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().


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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜