You could use the this.ViewData.ModelMetadata.Properties
collection and call the GetDisplayName
method to generate the header cell content. We do this generically in our code to render an arbitrary model as a table.
Edit:
To expand on this, I use a basic model that represents a table and only a table. I have 3 classes defined. I have a TableRowCell' class, a
TableRow' class (which is essentially a collection of TableRowCell
objects) and a Table
class.
public class Table
{
public Table(String name)
{
this.Name = name;
this.ContentRows = new List<TableRow>();
this.HeaderRow = new TableRow();
this.FooterRow = new TableRow();
}
public IList<TableRow> ContentRows
{
get;
private set;
}
public TableRow FooterRow
{
get;
private set;
}
public TableRow HeaderRow
{
get;
private set;
}
public String Name
{
get;
private set;
}
}
When I have a view model that contains a collection of objects that I want to display in a table I call first an HtmlHelper
extension that converts that collection into a Table
object. Inside that method I iterate over a call to ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TModel)).Properties..Where(item => item.ShowForDisplay)
to get a collection of metadata objects used to generate the header cells. I then iterate over the collection of items and call ModelMetadataProviders.Current.GetMetadataForType(() => item, typeof(TModel)).Properties..Where(item => item.ShowForDisplay)
to get a collection of metadata objects used to generate the content cells.
Technically, my HtmlHelper
extension method actually returns a TableBuilder
object which will has a method called Render
on it which generates the html. That setup has served me well so far.