0
string[] showProperties = {"id", "name"};
@*
user has many properties, id, name, address, etc...
*@

<!-- now I just want to show the properties in the shownProperties list -->
@for (int j = 0; j < showProperties.Length; j++)
{
    <td>
       @user.showProperties[j]
    </td>
}

Normally I would do @user.id or @user.name to display, but in this case, [property] is dynamically pulled by the value of the array of showColumns.

The @user.showProperties[j] above won't work, Razor won't recognize the id as the property for example. Is there a way to inject 'id' into @user.[] as @user.id?

How do I do @user.(mydynamicproperty) properly?

Chris Lists
  • 91
  • 1
  • 5

1 Answers1

0

If your dynamic object is of type ExpandoObject, then its as simple as casting the dynamic object to type IDictionary<string, object> because ExpandoObject's implement that interface. Here is an example razor program:

@{

    string[] showColumns = new string[3] {"Property1", "Property2", "Property3"};
    dynamic myobject = new System.Dynamic.ExpandoObject();
    myobject.Property1 = "First Property!";
    myobject.Property2 = "Second Property!";
    myobject.Property3 = "Third Property!";

    for (int i = 0; i < showColumns.Length; i++)
    {
        var propertyValues = (IDictionary<string, object>)myobject;
        <p>@propertyValues[showColumns[i]]</p>
    }
}

If your object is not an ExpandoObject, then it might be a little more difficult. Difficult, but not impossible. Look at the answer here.

Community
  • 1
  • 1
Icemanind
  • 47,519
  • 50
  • 171
  • 296
  • my object is not ExpandoObject, the link given is not relatively helpful. I edited my question to be more clearer, hopefully. Can you take a look and see if you can give it another try? Thanks – Chris Lists May 15 '15 at 12:55
  • @ChrisLists - I'm still not sure what you are trying to do? In your example, what is `showProperties`? Show your definition for that variable. – Icemanind May 16 '15 at 03:16
  • @ChrisLists - It sounds like you just want to reflect. Try this: `user.GetType().GetProperty(showProperties[i]).GetValue(user, null);` – Icemanind May 17 '15 at 00:12