Note that there are some explanatory texts on larger screens.

plurals
  1. POGeneric HtmlHelper for creating html table from list of any type
    text
    copied!<p>I would like to create a HtmlHelper for creating a html table. I would like the helper to be able to take a list of any type of object and a list of the properties of the object to display as columns. Something like this:</p> <pre><code>public static HtmlString Table(this HtmlHelper helper, List&lt;T&gt; data, List&lt;string&gt; 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()); } </code></pre> <p>This code will of course not work, but I am wondering if it would be possible to make something similar? And how I might go about doing that.</p> <p><strong>EDIT:</strong> </p> <p>I chose the following solution, the idea was that the table should only contain the elements specified in the headers list, so this is what i came up with:</p> <pre><code>public static HtmlString Table&lt;T&gt;(this HtmlHelper helper, List&lt;T&gt; data, List&lt;string&gt; 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()); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload