Send a list of data in a viewbag and receive in a foreach in the view

Asked

Viewed 1,714 times

1

The query data is correct, but I cannot return the data to the view.

Controller:

var disponib = (from d in db.Disponibilidade
                join c in db.Catequista on d.CatequistaID equals c.CatequistaID
                where c.CatequistaID == d.CatequistaID && d.CatequistaID == id
                select new
                {
                    AnoPastoral = d.AnoPastoral,
                    DiaDisponivel = d.DiaDisponivel,
                    HoraDisponivel = d.HoraDisponivel,
                    HoraFim = d.HoraFim,
                    Observacoes = d.Observacoes,
                }).ToList();

ViewBag.Disponibilidade = disponib;

View:

@model WebAppCatechesis2.Models.Catequista

@foreach (var item in ViewBag.Disponibilidade)
{    
    //  ???
}
  • Ever tried to give a cast in Viewbag? Something like: ViewBag.Disponibilidade as ICollection<SUACLASSE>?

  • @Marllonnasser the foreach already cast .

  • Some solution?

  • Can’t you create a Viewmodel class that contains a class with a list of availabilities? This would make the development flow "more correct". Viewbag may not be the best option.

2 answers

1

var lista = linq.toList<suaClasse>();
ViewBag.MinhaView = lista;


@foreach (var item in ViewBag.MinhaView as IList<suaClasse>) {
   //-- Codigo
}

Line = (your query expression)

It is feasible to put before the foreach a check of the type:

@if(ViewBag.MinhaView != null) {
   //-- foreach aqui
}

I don’t know about your application, but there’s how you pass an object to the view maybe it’s even better:

return PartialView("NomeDaView", ObjetoDeClasse);

in View accesses with

@model ObjetoDeClasse

@foreach(var item in Model){ 
   //-- Codigo
}

I hope to help.

1


Problem solved with the query

var disponib = (from d in db.Disponibilidade
                            join c in db.Catequista on d.CatequistaID equals c.CatequistaID
                            where c.CatequistaID == d.CatequistaID && d.CatequistaID == id
                            select d);

            ViewBag.Disponibilidade = disponib;
  • Don’t forget to mark your answer with accepted to close the question.

Browser other questions tagged

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