Best Practices for Writing HTML in Web Parts?
Something that's as puzzling as the Cadbury secret (and we all know that us programmers figured that out long ago) is just what's the best way to write out HTML in Web Parts? So call me masochistic but I write Web Parts with code. Yes, it's ugly. Yes, it's painful. Yes, you could use something cool like SmartPart or load the controls yourself (but that brings on a host of other issues like Code Access Security so we won't go into that).
For those of us that hold true to the "old fashioned" way, what's the best way to write all that code out? Consider these two approaches that writes out a label and control in a row for a form:
private void RenderRow(HtmlTextWriter output, Label label, WebControl control)
{
output.Write("<tr><td class=\"ms-formlabel\" valign=\"top\" nowrap=\"true\">");
label.RenderControl(output);
output.Write("</td><td class=\"ms-formbody\">");
control.RenderControl(output);
output.Write("</td></tr>");
}
private void RenderRow(HtmlTextWriter output, Label label, WebControl control)
{
output.RenderBeginTag("tr");
output.RenderBeginTag("td");
output.AddAttribute("class", "ms-formlabel");
output.AddAttribute("valign", "top");
output.AddAttribute("nowrap", "true");
label.RenderControl(output);
output.RenderEndTag();
output.RenderBeginTag("td");
output.AddAttribute("class", "ms-formbody");
control.RenderControl(output);
output.RenderEndTag();
output.RenderEndTag();
}