Benjamin
Benjamin

Reputation: 3224

How can I access an object's property from the PropertyInfo?

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>;
    }
}

Upvotes: 0

Views: 1575

Answers (2)

Quintin Robinson
Quintin Robinson

Reputation: 82325

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499860

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" });
}

Upvotes: 3

Related Questions