Friday, October 31, 2008

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("");

label.RenderControl(output);

output.Write("");

control.RenderControl(output);

output.Write("");

}



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();

}



Both output exactly the same HTML. Does it matter? The first approach is less lines but is it any more (or less) readable? Or maybe everything should be built up in a StringBuilder class and slammed out to the HtmlTextWriter? Or is it simply whatever is readable or maintainable works? Looking for your thoughts, ideas, suggestions, rants, assorted concealed lizards of any kind.

No comments: