0

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>;
    }
}
Benjamin
  • 3,134
  • 6
  • 36
  • 57

2 Answers2

3

Well, you need an instance to call it on - presumably that's Model.Entity in this case. You need the GetValue method. However, it's going to be quite tricky - because you need two things:

  • You need the value to be iterable by foreach
  • You need each item to have an Id property.

If you're using C# 4 and .NET 4, you can use dynamic typing to make it a bit simpler:

IEnumerable values = (IEnumerable) propertyInfo.GetValue(Model.Entity, null);
@foreach(dynamic item in values) {
    @Html.Action("Edit", new { Id = item.Id, typeName = "Item" });
}

Or even:

dynamic values = propertyInfo.GetValue(Model.Entity, null);
@foreach(dynamic item in values) {
    @Html.Action("Edit", new { Id = item.Id, typeName = "Item" });
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you very much. You saved me a lot of time by answering questions I didn't even know I would soon have to ask next. – Benjamin Aug 05 '11 at 20:18
1

When you say get the "actual property of the object" if you are referring to the value of the property then you can do something like below.

var item = in propertyInfo.GetValue(Model.Entity, null);

However if you don't have the proper type resolved (which should be object in the above example using var for inference) you will not be able to access the Id property of the value without further reflection or a different dynamic method for accessing the data.

Edit: modified the example not to be in the foreach as @Jon Skeet pointed out it wouldn't compile without the cast and this is moreover to demonstrate retrieving a value from PropertyInfo

Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132