HtmlTable和TagBuilder之间的区别(“表”)

只是想知道这两者之间的区别是什么,当我在HtmlHelper中构建表时,它们中的一个或另一个的好处是什么

HtmlTable table = new HtmlTable(); 

和:

 TagBuilder table = new TagBuilder("table"); 

这和这个问题大致相同,

为什么使用TagBuilder而不是StringBuilder?

但我更想知道这两者之间的区别。

主要区别在于HtmlTable

元素的所有有效HTML属性(例如WidthHeightCellSpacing等)提供了类型化和正确命名的属性。 它还有Rows属性,它是HtmlTableRow对象的类型集合,每个对象都重新发送一个

元素。

TagBuilder是一个更通用的API,它当然可以用于构建HTML

但是你需要以更少类型安全且不易阅读的方式做更多的工作。

HmlTableTagBuilder不支持的方式的一个具体示例是在

元素的width=""属性的设置中。

使用HtmlTable

 HtmlTable htmlTable = new HtmlTable(); htmlTable.Width = "100px"; 

使用TagBuilder

 TagBuilder tagBuilder = new TagBuilder("table"); tagBuilder.Attributes["width"] = "100px"; 

请注意,对于TagBuilder ,元素的名称, table和属性的名称width都是字符串,它们引入了两个在使用HtmlTable时不会出现的错误(拼写错误)机会。