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:
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());
}
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.
EDIT:
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:
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());
}
Hi I updated your code for the .NET core version. good luck
public static IHtmlContent Table<T>(IList<T> data, IList<(string propertyName, string colName)> headers)
{
//Tags
var table = new TagBuilder("table");
var tr = new TagBuilder("tr");
//Add headers
foreach (var s in headers)
{
var th = new TagBuilder("th");
th.InnerHtml.Append(s.colName);
tr.InnerHtml.AppendHtml(th);
}
table.InnerHtml.AppendHtml(tr);
//Add data
foreach (var d in data)
{
tr = new TagBuilder("tr");
foreach (var h in headers)
{
var td = new TagBuilder("td");
td.InnerHtml.Append( d.GetType().GetProperty(h.propertyName).GetValue(d, null)?.ToString());
tr.InnerHtml.AppendHtml(td);
}
table.InnerHtml.AppendHtml(tr);
}
return table;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With