Asp.net best practice string concatenation

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

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

      

Now that I start testing a bit, I have a method that works 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 a real solution, the return is a concatenation of about 10 fields, which are very long since they are content.

I in no way think this is the best solution, but what is it? StringBuilder? Can I write each part in turn to the site, avoiding concatenation in the method? Is server div better?

Edit: Forgot to have some of my sections have simple (limited) html in them like paragraph, list ... This allows me to easily create web and print documents, I just use different stylesheets.

+1


source to share


3 answers


I would use <asp:Literal runat="server" enableViewState="false" id="leaflet" />

. This does not generate any tags on the page and does not fill all the text in the ViewState.

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



Another solution would be to see if you can do some fixed markup on the page and put the contents of each DB field in its own control ( <asp:Literal />

?).

+4


source


I would use either string.Format if the number of fields is fixed (and relatively small), or StringBuilder otherwise. Code readability will be my guide, and even better performance. You might also consider abstracting this in the UserControl if you plan on reusing it. Then you can give it custom properties and build the rendering logic in the control so it doesn't repeat itself.



+1


source


Various people compare this - the iirc format is good for <4 items, simple concatenates for <7, stringbuilding above that.

I highly recommend not creating HTML as btw strings.

0


source







All Articles