How to return dynamic list?

3

How to return a List<dynamic> in ASP.NET MVC 5 and EntityFramework 6

For example I have an Object named User and mapped in my EDMX, when I do to bring the data dynamically type make an advanced query without returning an object of type User.

Note: this is a View the vwCase

select top 5 SUM(vrLancamento),nmTipoDocumento from vwCaixa group by nmTipoDocumento

I did so:

public IList<dynamic> resumoCaixa()
        {
            IList<dynamic> lista = new List<dynamic>();

            TimeSpan time = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);



            using (var ctx = new dbProClinicEntities())
            {
               var t = ctx.vwCaixa.GroupBy(g => new { documento = g.nmTipoDocumento, pago = g.dtPago, valor = g.vrLancamento })
               .Select(x => new { pago = x.Key.pago, tipoDocumento = x.Key.documento, vrLancamento = x.Sum(f => f.vrLancamento) })
               .Take(5).ToList();

                foreach(var f in t)
                {
                    lista.Add(f);
                }
            }

            return lista.ToList();
        }

In the Controller I'm returning a ViewBag:

 public ActionResult Index()
    {
        AdminDAO dao = new AdminDAO();
        ViewBag.Caixa caixa = dao.resumoCaixa();
        return View();
    }

In the View I'm doing this:

<table class="table list">
                <tbody>
                    @foreach(var caixa in ViewBag.Caixa)
                    { 
                    <tr>
                        <td>
                            <a href="#"><p class="title">@caixa.vrLancamento</p></a>
                            <p class="info">@caixa.tipoDocumento</p>
                        </td>
                   </tr>
                        }
                </tbody>
</table>

But it gives the following error:

    
asked by anonymous 24.12.2014 / 18:16

1 answer

2

In your example you are not passing the list as a model, but the view bag. It is also not allowed to pass an anonymous class as a model for the view. Create a view model and use it in the linq query. Ex.:

var t = ctx.vwCaixa.GroupBy(g => new { documento = g.nmTipoDocumento, pago = g.dtPago, valor = g.vrLancamento }).Select(x => new **MINHAVIEWMODEL** { pago = x.Key.pago, tipoDocumento = x.Key.documento, vrLancamento = x.Sum(f => f.vrLancamento) }).Take(5).ToList();

and pass the variable t as a model using return View(t);

obs: do not forget to put in the first line of the view @model IEnumerable<MINHAVIEWMODEL>

    
30.12.2014 / 14:22