Recover property of Object Anonymous C# Razor

Asked

Viewed 595 times

1

I am working with MVC4 and Restsharp for data access via API Rest,

My return is an object of the type Object but I cannot recover a specific property of this object.

How can I access the property?

Follow view code in which I need to recover 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>
  • 1

    You can show the code you currently have to illustrate the problem?

  • You have already tried the cast for the desired object type?

  • I need this property to display in the view. I couldn’t do the cast at all.

  • Why not change the return type of the action to the object type?

  • Forgive my ignorance, but I could be more clear?

  • I explained it wrong. Which is the type of the variable Model?

Show 1 more comment

1 answer

1

The code is already correct. You can perform some extra 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);
}

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

  • 1

    Guy worked. Thank you very much.

  • I think using Dynamic Typing or Reflection to create a view is wrong and leads to hard to maintain code... Model does not seem to be the right kind, and that should be corrected.

  • It may be, but the object returned by Restsharp is anonymous. It has no type. He may do, but the answer correctly solves the proposed by the question.

  • Yes, the answer answers the question and solves the problem, I agree. But I think the OP is trying to solve the wrong problem. The problem he needs to solve is how to pass a correctly typed object to the view instead of an anonymous object.

  • The API’s Getall method cannot automatically turn into list when I select the type of object in the employee case, it only assigns when working with the model this way public Object responsavel { get; set; } I need to recover a specific attribute in the view and the code above did this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.