0

I have this linq query

var impuestos = conceptos
    .GroupBy(a => a.ImpuestoId)
    .Select(a => new
    {
        id = a.Key,
        montoImpuesto = a.Sum(b => b.montoImpuesto), 
        impuestoNombre = a.FirstOrDefault().impuesto.Nombre,
        impuestoTipo = a.FirstOrDefault().impuesto.Tipo,
    })
    .ToList();

ViewBag.grupo = impuestos;

And I want to show it in a view. It tried this

@foreach (var impuesto in ViewBag.grupo)
{
    <tr>
        <td>
            @impuesto.id
        </td>
        <td>
            @impuesto.Nombre
        </td>
        <td>
            @impuesto.montoImpuesto
        </td>
    </tr>
}

But I get an error telling there is no definition for 'id' in the object. I already tried adding a foreach inside the main foreach, but I get different errors. What is the correct way?

ekad
  • 14,436
  • 26
  • 44
  • 46
Allfarid Morales García
  • 1,455
  • 2
  • 17
  • 27

2 Answers2

0

An object once added to ViewBag gets converted to type object (boxed). You will have to unbox it to specific type before using. The select query returns an anonymous object, instead create a entity class, which is used to return grouped collection. Convert ViewBag.grupo to IEnumerable<T> on the View and then use it in the foreach loop.

Amit
  • 25,106
  • 25
  • 75
  • 116
0

You can't use anonymous objects as models (well, you can, but they're passed as object and you can't cast them to the original type, since it's anonymous!). Either create a model class, or use a hack like this one.

Community
  • 1
  • 1
Gabriel Negut
  • 13,860
  • 4
  • 38
  • 45