I’m imagining that this will come down to personal preference but which way would you go?
StringBuilder markup = new StringBuilder(); foreach (SearchResult image in Search.GetImages(componentId)) { markup.Append(String.Format('<div class=\'captionedImage\'><img src=\'{0}\' width=\'150\' alt=\'{1}\'/><p>{1}</p></div>', image.Resolutions[0].Uri, image.Caption)); } LiteralMarkup.Text = markup.ToString();
Vs.
StringBuilder markup = new StringBuilder(); foreach (SearchResult image in Search.GetImages(componentId)) { markup.Append(String.Format(@'<div class=''captionedImage''><img src=''{0}'' width=''150'' alt=''{1}''/><p>{1}</p></div>', image.Resolutions[0].Uri, image.Caption)); } LiteralMarkup.Text = markup.ToString();
Or should I not be doing this at all and using the HtmlTextWriter class instead?
EDIT: Some really good suggestions here. We are on 2.0 framework so LINQ is not available
Another vote for ‘AppendFormat’. Also, for the sake of the server code I might put up with single quotes here to avoid the need to escape anything:
Finally, you may also want an additional check in there somewhere to prevent html/xss injection.
Another option is to encapsulate your image in a class:
This has the advantage of making it easy to re-use and add features to the concept over time. To get real fancy you can turn that class into a usercontrol.