Filipe Leite
Filipe Leite

Reputation: 1

Can´t acess Query information in my view with an anonymous type

Well, I have made a Linq Query, a Top 5 from my db, I can send this query to the view as expected, but when I try to access its fields, it says that my "object" doesnt have those parameters, even tho I can see they arrive at the foreach cycle, as Im showing at the image

My view

   @foreach (var item in ViewBag.TOPEMPRESASMAISPROCURADAS)
                {
                    <tr>
                        <td>@item.Nome</td>
                        <td>@item.Numero_Estagios</td>
                    </tr>
                }

my controller:

 ViewBag.TOPEMPRESASMAISPROCURADAS = Empresas.Select(emp => new { emp.Nome, Numero_Estagios = Estagios
                .Where(x => x.Empresa.EmpresaID == emp.EmpresaID && x.AnoLetivo == AnoLetivo).Count() })
                .OrderBy(y => y.Numero_Estagios).Take(5);

Well, as you can see the foreach is receiving the item and its info as it should but I cant use item.Nome or item.NumeroEstagios, why is that? I would really enjoy to have some help, im a newbie here. Thanks

Upvotes: 0

Views: 37

Answers (1)

Erik Philips
Erik Philips

Reputation: 54618

If you're going to be using Model-View-Controller pattern you should actually create a Model that represents the data you want the View to present. The ViewBag should be avoided.

public class MyClass
{ 
  public <type> Nome { get; set; }
  public <type> Numero_Estagios { get; set; }
}

public class IndexVM
{
  public IEnumerable<MyClass> items { get; set; }
}

Then

var model = new IndexVM
{
  items = Empresas
    .Select(emp => new MyClass { 
        Nome = emp.Nome, 
        Numero_Estagios = Estagios.Where(x => x.Empresa.EmpresaID == emp.EmpresaID && x.AnoLetivo == AnoLetivo).Count() 
    })
    .OrderBy(y => y.Numero_Estagios)
    .Take(5)
    .ToList()
}

return View(model);

and in your view:

@model IndeVM

@foreach (var item in Model.Items)
{
  <tr>
    <td>@item.Nome</td>
    <td>@item.Numero_Estagios</td>
  </tr>
}

Upvotes: 2

Related Questions