This is for an ASP.NET MVC 4 application in a Razor view. I am passing a model to a partial view and am trying to iterate through a given list of properties contained in the model to be displayed as a table.
Given something like List<string> propertyNames, in this table, I would like to output the DisplayNameFor and the value of the property in a structure like so:
<tr>
<th>@Html.DisplayNameFor(Model.property)</th>
<td>@Model.property</td>
</tr>
I'll have to do this a few times in the partial because different properties correspond to different div elements in the partial where different tables will be inserted so I've created a helper and this is where I get hung up. First, the only way I know how to do this is reflection, and I have read that reflection is expensive especially for just doing one property at a time. Also, using this method, I can't get @Html.DisplayNameFor to work correctly because, using reflection, I don't quite know the syntax:
@helper IterateDetailPropertyNames(List<string> propertyNames) {
foreach (var property in propertyNames)
{
<tr>
<th>
@Html.DisplayNameFor(m => m.GetType().GetProperty(property).GetValue(Model, null));
@*Error: Templates can be used only with field access, property access...*@
</th>
<td>
@Model.GetType().GetProperty(property).GetValue(Model, null)
</td>
</tr>
}
}
How can I make this work and improve this?
@Html.DisplayNameFor(m => m[property]);no reflection involved...ModelMetadatato access all the properties of the model, including its display name. Are you just wanting to display each properties display name and the property value in a table?ModelMetadatais the way to go. No time just now, but I'll add answer in 30 min or so. In the meantime, you might be interested in this project - have not go around to writing the docs yet, but that is described here