Retrieve property of an Anonymous Object C # Razor

1

I'm working with MVC4 and RestSharp for data access via API Rest,

My return is an object of type Object but I can not retrieve a specific property of this object.

How can I access the property?

Here is the code for the view where I need to retrieve the property.

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.descricao)
    </td>
    <td>
        @{
            var responsavel = item.responsavel.GetType().GetProperty("nome").GetValue(item.responsavel, null);
            @Html.DisplayFor(modelItem => item.responsavel);
         }
    </td>
    <td>
        @Html.ActionLink("Editar", "Edit", new { id=item.id }) |
        @Html.ActionLink("Detalhes", "Details", new { id=item.id }) |
        @Html.ActionLink("Deletar", "Delete", new { id=item.id })
    </td>
</tr>
    
asked by anonymous 23.04.2015 / 15:17

1 answer

1

The code is already correct. You can perform a few more checks to avoid NullReferenceException when accessing the property:

dynamic responsavel = item.responsavel;
var prop = responsavel.GetType().GetProperty("nome");
var nome = ""
if (prop != null) {
    nome = prop.GetValue(responsavel, null);
}

As you do not have a specified type for the object (possibly it is anonymous), dynamic "sets" a typing for the object.

    
23.04.2015 / 15:41