问题
Just wondering what the difference is between these two and what the benefit for one or the other of them would be when I build my table in my HtmlHelper
HtmlTable table = new HtmlTable();
and:
TagBuilder table = new TagBuilder("table");
This is more or less the same as this question,
Why use TagBuilder instead of StringBuilder?
but I'm wondering more specifically about the difference between these two .
回答1:
The main difference is that HtmlTable
provides typed and correctly named properties for all the valid HTML attributes of the <table>
element (e.g. Width
, Height
, CellSpacing
, etc). It also has the Rows
property which is a typed collection of HtmlTableRow
objects which each reresent a <tr>
element.
TagBuilder
is a much more generic API which could certainly be used to construct an HTML <table>
but you'd need to do more work in a less type safe and less easy to read way.
One concrete example where HmlTable
helps in a way that TagBuilder
does not is in the setting of the width=""
attribute on the <table>
element.
With HtmlTable
:
HtmlTable htmlTable = new HtmlTable();
htmlTable.Width = "100px";
With TagBuilder
:
TagBuilder tagBuilder = new TagBuilder("table");
tagBuilder.Attributes["width"] = "100px";
Note that with TagBuilder
both the name of the element, table
, and the name of the attribute, width
, are strings which introduce two opportunities for error (misspellings) that do not occur when using HtmlTable
.
来源:https://stackoverflow.com/questions/3043800/difference-between-htmltable-and-tagbuildertable