When I foreach through an object’s properties and end up with a PropertyInfo, how can I access the actual property of the object?
@foreach(var propertyInfo in Model.Entity.GetType().GetProperties()) {
if (propertyInfo.PropertyType != typeof(string) &&
propertyInfo.PropertyType.GetInterface(typeof(IEnumerable<>).Name) != null) {
<div>
@foreach(var item in propertyInfo/*Need Actual Property Here*/) {
@Html.Action("Edit", new { Id = item.Id, typeName = "Item" });
}
</div>;
}
}
Well, you need an instance to call it on – presumably that’s
Model.Entityin this case. You need theGetValuemethod. However, it’s going to be quite tricky – because you need two things:foreachitemto have anIdproperty.If you’re using C# 4 and .NET 4, you can use dynamic typing to make it a bit simpler:
Or even: