views:

725

answers:

3

I am trying to find the best practice for generating and outputting html which would require a database query first to obtain the info. Currently in the aspx page I have a div with runat server:

<div runat="server" id="leaflet"></div>

Now just as a start to do a bit of testing I have a method that runs on page_load that basically does:

private void BuildLeaflet(string qnid)
    {
    //gets leaflet details
    QueryLeafletDetails();
    //return concatenated content string
    leaflet.InnerHtml "<h1>" + dr["LSC Descriptor"] + "</h1>";
    }

In the real solution the return is a concatenation of about 10 fields some very long as they are content.

I don't by any means think this is the best solution, but what is? A StringBuilder? Can I Write Each Part in turn to the site avoiding the concatenation in the method? Is the server div even best?

Edit: Forgot to put some of my content sections have simple (limited) html in them already such as paragraph, list... This allows me to easily produce documents for web and printing, I just use different stylesheets.

+1  A: 

I'd use either string.Format, if the number of fields is fixed (and relatively small), or a StringBuilder, otherwise. Readability of the code would be my guide, less so performance. You might also want to think about abstracting this out into a UserControl if you plan to reuse it. Then you could give it settable properties and build the render logic into the control to avoid repeating yourself.

tvanfosson
+4  A: 

I would use <asp:Literal runat="server" enableViewState="false" id="leaflet" />. This doesn't generate any tags on the page, and doesn't stuff all the text in the ViewState.

And yes, use StringBuilder if you need to concatenate many long strings. This will be way more memory efficient.

The other solution would be to see if you can make some fixed markup on the page and put the contents of each DB field in it's own control (<asp:Literal />?).

Vilx-
A: 

Various people have benchmarked this - iirc format is fine for <4 items, simple concats for <7, stringbuilding above that.

I strongly advise against creating HTML as strings btw.

annakata
With string.Format you will find out pretty quickly if you've missed "concatenating" a field even if it is normally null. You can improve readability by storing the format as a single string constant elsewhere in the code and just referencing it locally.
tvanfosson
I don't see how your first point is relevant (you'll find out *at exactly the same time* if you're stringbuilder or + is wrong) and I don't see how your second point relates to my post in particular? Obviously format has advantages or it wouldn't exist.
annakata