OK, I decided to do a little test in my own code base.
I compared these two methods to create the same exact final HTML:
- Manually generating the html using a StringBuilder
- Using multiple TagBuilders and nesting the content
Manually generating the html using a StringBuilder:
var sb = new StringBuilder();
sb.AppendLine("<div class='control-group'>");
sb.AppendFormat(" <label class='control-label' for='{0}_{1}'>{2}</label>", propObj.ModelType, propObj.ModelProperty, propObj.LabelCaption);
sb.AppendLine(" <div class='controls'>");
sb.AppendFormat(" <input id='{0}_{1}' name='{0}[{1}]' value='{2}' />", propObj.ModelType, propObj.ModelProperty, propObj.PropertyValue);
sb.AppendLine(" </div>");
sb.AppendLine("</div>");
return new HtmlString(sb.ToString());
Using multiple TagBuilders and merging the content:
TagBuilder controlGroup = new TagBuilder("div");
controlGroup.AddCssClass("control-group");
TagBuilder label = new TagBuilder("label");
label.AddCssClass("control-label");
label.InnerHtml = propObj.LabelCaption;
TagBuilder controls = new TagBuilder("div");
TagBuilder input = new TagBuilder("input");
input.Attributes["id"] = propObj.ModelType + "_" + propObj.ModelProperty;
input.Attributes["name"] = propObj.ModelType + "[" + propObj.ModelProperty + "]";
input.Attributes["value"] = propObj.PropertyValue;
controls.InnerHtml += input;
controlGroup.InnerHtml += label;
controlGroup.InnerHtml += controls;
return new HtmlString(controlGroup.ToString());
To me, #1 is easier to read and much more concise, but I can appreciat the structure of #2 also.