我制定了以下法典,以便从以下阵列中得出一个表。
var fruit = new string[] { "apple", "pear", "tomato" };
public static MvcHtmlString CustomGrid(this HtmlHelper htmlHelper, String Id, IList Items, IDictionary<string, string> Attributes)
{
if (Items == null || Items.Count == 0 || string.IsNullOrEmpty(Id))
return MvcHtmlString.Empty;
return BuildGrid(Items, Id, Attributes);
}
public static MvcHtmlString BuildGrid(IList Items, string Id, IDictionary<string, string> attributes)
{
StringBuilder sb = new StringBuilder();
BuildHeader(sb, Items[0].GetType());
foreach (var item in Items)
{
BuildTableRow(sb, item);
}
TagBuilder builder = new TagBuilder("table");
builder.MergeAttributes(attributes);
builder.MergeAttribute("name", Id);
builder.InnerHtml = sb.ToString();
var Tag = builder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(Tag);
}
public static void BuildTableRow(StringBuilder sb, object obj)
{
Type objType = obj.GetType();
sb.AppendLine(" <tr>");
foreach (var property in objType.GetProperties())
{
sb.AppendFormat(" <td>{0}</td>
", property.GetValue(obj, null));
// sb.AppendFormat(" <td>{0}</td>
", obj);
}
sb.AppendLine(" </tr>");
}
public static void BuildHeader(StringBuilder row, Type p)
{
row.AppendLine(" <tr>");
foreach (var property in p.GetProperties())
{
row.AppendFormat(" <th>{0}</th>
", p.Name);
}
row.AppendLine(" </tr>");
}
但它没有做任何事情。 我也这样做:
Html.CustomGrid("myTable", (System.Collections.IList)fruit, null);
请提供解决办法。