Search code examples
c#readabilityhtml-generation

Which Method Do You Find More Readable To Output Dynamic HTML?


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


Solution

  • 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:

    StringBuilder markup = new StringBuilder();
    
    foreach (SearchResult image in Search.GetImages(componentId))
    {
        markup.AppendFormat(
            "<div class='captionedImage'><img src='{0}' width='150' alt='{1}'/><p>{1}</p></div>", 
            image.Resolutions[0].Uri, image.Caption
          );
    }
    
    LiteralMarkup.Text = markup.ToString();
    

    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:

    public class CaptionedHtmlImage
    {  
        public Uri src {get; set;};
        public string Caption {get; set;}
    
        CaptionedHtmlImage(Uri src, string Caption)
        {
            this.src = src;
            this.Caption = Caption;
        }
    
        public override string ToString()
        {
            return String.Format(
                "<div class='captionedImage'><img src='{0}' width='150' alt='{1}'/><p>{1}</p></div>"
                src.ToString(), Caption
              );
        }
    }
    

    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.