Question:
good morning everyone,
I'm new to development, and I'm having trouble passing a list from a controller query to a view. I did some research and all the ways I found didn't help much, if anyone can help me in this I'll be grateful.
Here's controller:
namespace DinheiroControlado.Controllers
{
public class RelatorioController : Controller
{
//
// GET: /Relatorio/
private DinheiroControladoBD db2 = new DinheiroControladoBD();
public ActionResult Index()
{
var cookie = DinheiroControlado.Repositorios.RepositoriosUsuarios.VerificaSeOUsuarioEstaLogado();
var dados = (from d in db2.Movimentacoes
join c in db2.Categorias on d.IDCategoria equals c.IDCategoria
where d.IDUsuario == cookie.IDUsuario
group d by c.Descricao into g
select new { Categoria = g.Key, Valor = g.Sum(d => d.Valor)}).Take(5);
ViewBag.grafico = dados;
return View();
}
}
}
View follows:
@{
ViewBag.Title = "Index";
Layout = "~/Views/Layout2.cshtml";
}
<h2>Index</h2>
<table>
<tbody>
@{foreach (var item in ViewBag.grafico)
{
<tr>
<td>
@item.Categoria
</td>
<td>
@item.Valor
</td>
</tr>
}
}
</tbody>
Error that is occurring:
Erro de Servidor no Aplicativo '/'. 'object' não contém uma definição para 'Categoria' Descrição: Ocorreu uma exceção sem tratamento durante a execução da atual solicitação da Web. Examine o rastreamento de pilha para obter mais informações sobre o erro e onde foi originado no código.
Detalhes da Exceção: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' não contém uma definição para 'Categoria'
Erro de Origem:
Linha 11: <tr>
Linha 12: <td>
Linha 13: @item.Categoria
Linha 14: </td>
Linha 15: <td>
Arquivo de Origem: c:\TCC\C#\DinheiroControlado\DinheiroControlado\Views\Relatorio\Index.cshtml Linha: 13
Rastreamento de Pilha:
Answer:
I advise you to do the following:
- Create a class to encapsulate chart information
- Add a data model to this view
You can do this as follows:
//Classe para o encapsulamento
public class ItemGrafico
{
public string Categoria { get; set; }
public decimal Valor { get; set; }
}
//Altere o select para new ItemGrafico
var dados = (from d in db2.Movimentacoes
join c in db2.Categorias on d.IDCategoria equals c.IDCategoria
where d.IDUsuario == cookie.IDUsuario
group d by c.Descricao into g
select new ItemGrafico { Categoria = g.Key, Valor = g.Sum(d => d.Valor)}).Take(5);
In your action on the controller do the following:
return View("NomeDaSuaView", dados);
And finally in your view, make the following changes:
On the first line:
@model IEnumerable<seu.namespace.completo.ItemGrafico>
and in foreach
change to look like this:
@foreach (var item in Model)
{
<tr>
<td>
@item.Categoria
</td>
<td>
@item.Valor
</td>
</tr>
}
By making these changes you should be able to do what you want without further problems.