我正在玩从 System.Web.UI.WebControls.Table/Cell/Row 派生并且无法让 HtmlTextWriter.AddAttribute 工作:
桌子:
public class Table : System.Web.UI.WebControls.Table
{
public string Title { get; set; }
public bool Sorted { get; set; }
public Table()
{
}
}
表头行:
public class TableHeaderRow : System.Web.UI.WebControls.TableHeaderRow
{
public TableHeaderRow()
{
this.TableSection = TableRowSection.TableHeader;
this.ClientIDMode = System.Web.UI.ClientIDMode.Static;
}
}
表头单元格:
public class TableHeaderCell : System.Web.UI.WebControls.TableHeaderCell
{
public TableHeaderCell()
{
}
public override void RenderBeginTag(HtmlTextWriter writer)
{
AddAttributesToRender(writer);
writer.AddAttribute("test", "whee");
writer.WriteBeginTag("th");
//writer.WriteAttribute("test", "whee");
writer.WriteLine('>');
}
public override void RenderEndTag(HtmlTextWriter writer)
{
writer.WriteEndTag("th");
writer.WriteLine();
}
}
用法:
<Internal:Table ID="somethingTbl" runat="server" Title="A Table" Sorted="true">
<Internal:TableHeaderRow>
<Internal:TableHeaderCell>
Stuff
</Internal:TableHeaderCell>
<Internal:TableHeaderCell>
More Stuff
</Internal:TableHeaderCell>
<Internal:TableHeaderCell>
Less Stuff
</Internal:TableHeaderCell>
</Internal:TableHeaderRow>
</Internal:Table>
然后在cs中添加一些常规行。我得到以下部分输出:
<table id="activationsTbl">
<thead>
<tr>
<th>
Stuff
</th>
<th>
More Stuff
</th>
<th>
Less Stuff
</th>
</tr>
</thead><tbody test="whee" test="whee" test="whee">
...
正如你所看到的,属性被写在所有 th 标签之后的下一个开始标签(最后的 tbody 标签)。如果我使用注释掉的 WriteAttributes,那么它会被正确写入。如果没有任何其他行(因此没有<tbody>
),则属性不会写入任何其他标签。