Generic HtmlHelper to create an html table from a list of any type

I would like to create an HtmlHelper to create an html table. I would like the helper to be able to take a list of objects of any type and a list of object properties for display in columns. Something like that:

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 = dhToString(); tr.InnerHtml += td.ToString(); } sb.Append(tr.ToString()); } table.InnerHtml = sb.ToString(); return new HtmlString(table.ToString()); } 

This code, of course, does not work, but I wonder if it is possible to do something like this? And how can I do that.

EDIT:

I chose the following solution: the idea was that the table should contain only the elements indicated in the list of headers, so I came to the following:

 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()); } 
+7
source share
1 answer
 public HtmlTable BuildTable<T>(List<T> Data) { HtmlTable ht = new HtmlTable(); //Get the columns HtmlTableRow htColumnsRow = new HtmlTableRow(); typeof(T).GetProperties().Select(prop => { HtmlTableCell htCell = new HtmlTableCell(); htCell.InnerText = prop.Name; return htCell; }).ToList().ForEach(cell => htColumnsRow.Cells.Add(cell)); ht.Rows.Add(htColumnsRow); //Get the remaining rows Data.ForEach(delegate(T obj) { HtmlTableRow htRow = new HtmlTableRow(); obj.GetType().GetProperties().ToList().ForEach(delegate(PropertyInfo prop) { HtmlTableCell htCell = new HtmlTableCell(); htCell.InnerText = prop.GetValue(obj, null).ToString(); htRow.Cells.Add(htCell); }); ht.Rows.Add(htRow); }); return ht; } 

Give it a try. You need to call BuildTable<YourType>(list) .

+8
source

All Articles