我想创建一个 HtmlHelper 来创建一个 html 表。我希望助手能够获取任何类型的对象列表和对象属性列表以显示为列。像这样的东西:
public static HtmlString Table(this HtmlHelper helper, List<T> data, List<string> headers)
{
//Tags
TagBuilder table = new TagBuilder("table");
TagBuilder tr = new TagBuilder("tr");
TagBuilder td = new TagBuilder("td");
TagBuilder th = new TagBuilder("th");
//Inner html of table
StringBuilder sb = new StringBuilder();
//Add headers
foreach (var s in headers)
{
th.InnerHtml = s;
tr.InnerHtml += th.ToString();
}
sb.Append(tr.ToString());
//Add data
foreach (var d in data)
{
tr.InnerHtml = "";
foreach (var h in headers)
{
td.InnerHtml = d.h.ToString();
tr.InnerHtml += td.ToString();
}
sb.Append(tr.ToString());
}
table.InnerHtml = sb.ToString();
return new HtmlString(table.ToString());
}
这段代码当然行不通,但我想知道是否可以制作类似的东西?以及我将如何去做。
编辑:
我选择了以下解决方案,其想法是表格应该只包含标题列表中指定的元素,所以这就是我想出的:
public static HtmlString Table<T>(this HtmlHelper helper, List<T> data, List<string> headers)
{
//Tags
TagBuilder table = new TagBuilder("table");
TagBuilder tr = new TagBuilder("tr");
TagBuilder td = new TagBuilder("td");
TagBuilder th = new TagBuilder("th");
//Inner html of table
StringBuilder sb = new StringBuilder();
//Add headers
foreach (var s in headers)
{
th.InnerHtml = s;
tr.InnerHtml += th.ToString();
}
sb.Append(tr.ToString());
//Add data
foreach (var d in data)
{
tr.InnerHtml = "";
foreach (var h in headers)
{
td.InnerHtml = d.GetType().GetProperty(h).GetValue(d, null).ToString();
tr.InnerHtml += td.ToString();
}
sb.Append(tr.ToString());
}
table.InnerHtml = sb.ToString();
return new HtmlString(table.ToString());
}