View Code
1 public static class MVCHelpers
2 {
3 public static string Table(this HtmlHelper helper, string name, IList items, IDictionary<string, object> attributes)
4 {
5 if (items == null || items.Count == 0 || string.IsNullOrEmpty(name))
6 {
7 return string.Empty;
8 }
9
10 return BuildTable(name, items, attributes);
11 }
12
13 private static string BuildTable(string name, IList items, IDictionary<string, object> attributes)
14 {
15 StringBuilder sb = new StringBuilder();
16 BuildTableHeader(sb, items[0].GetType());
17
18 foreach (var item in items)
19 {
20 BuildTableRow(sb, item);
21 }
22
23 TagBuilder builder = new TagBuilder("table");
24 builder.MergeAttributes(attributes);
25 builder.MergeAttribute("name", name);
26 builder.InnerHtml = sb.ToString();
27 return builder.ToString(TagRenderMode.Normal);
28 }
29
30 private static void BuildTableRow(StringBuilder sb, object obj)
31 {
32 Type objType = obj.GetType();
33 sb.AppendLine("\t<tr>");
34 foreach (var property in objType.GetProperties())
35 {
36 sb.AppendFormat("\t\t<td>{0}</td>\n", property.GetValue(obj, null));
37 }
38 sb.AppendLine("\t</tr>");
39 }
40
41 private static void BuildTableHeader(StringBuilder sb, Type p)
42 {
43 sb.AppendLine("\t<tr>");
44 foreach (var property in p.GetProperties())
45 {
46 sb.AppendFormat("\t\t<th>{0}</th>\n", property.Name);
47 }
48 sb.AppendLine("\t</tr>");
49 }
50 }
使用方法: 1.如有命名空间先导入命名空间
2. @Html.Table(”TableName”, (IList)ViewBag.Model, null) 注意View.Bag中数据必须是Ilist