Using MVC3, I am creating a generic partial view which takes an IList as its model and then creates a table based on the ModelMetaData of the first object contained in the list. So far I can get the display names of each “thing” in the object but I can’t enumerate the actual fields/data in the object. Here is what I’ve tried:
@model System.Collections.IList
@if (this.Model.IsNullOrEmpty())
{
<p>No items found.</p>
}
else
{
<table>
<thead>
@{
ViewDataDictionary<object> viewData = new ViewDataDictionary<object>();
ModelMetadata metadata = ModelMetadata.FromLambdaExpression<object, object>(m => this.Model[0], viewData);
foreach (var property in metadata.Properties)
{
<th>@property.DisplayName</th>
}
}
</thead>
<tbody>
@foreach (var item in this.Model)
{
ViewDataDictionary<object> itemData = new ViewDataDictionary<object>(item);
<tr>
@foreach (var data in itemData)
{
<td>@data</td>
}
</tr>
}
</tbody>
</table>
}
The loop which creates the rows works but there is nothing in the ViewData. Thoughts?
You could use a RouteValueDictionary: