Conditional error in foreach using ASP.Net MVC

2

Partners of Stack Overflow in Spanish, I have the following error when doing this conditional ViewBag.p.Where(n => n.Lider == namelider in cycle foreach .

Here I show you part of my code:

<table class="table table-bordered">
    @foreach (var item in ViewBag.c)
    {
        var namelider = item.lider;
        <tr>
            <td>@item.nombres</td>
            <td>@item.lider</td>
            <td>@item.eje_funcional</td>
            @foreach(var peso in ViewBag.p.Where(n => n.Lider == namelider))
            {
                <td>@peso.Lider</td>
            }
        </tr>
    }
</table>

The error that appears to me is the following:

  

You can not use a lambda expression as an argument for a   operation sent dynamically without first converting it into a delegated type   or of expression tree.

I add driver queries:

ViewBag.c = (from p in db.Collaborators
             where p.grupo_lider == "NO"
             select p).ToList();

ViewBag.p = (from p in db.Objectives
             select p).ToList();

ViewBag.cal = (from p in db.CalificarColaboradors
               select p).ToList();
    
asked by ByGroxD 11.07.2017 в 23:42
source

2 answers

4

What happens is that ViewBag is a dynamic object ( dynamic ) that does not inherit properties or methods from the object that you originally used, you need to make a cast explicit to the object type original. This is called unboxing and it's pretty simple:

@foreach(var peso in ((List<SI_OldMutual.Models.Objectives>)ViewBag.p).Where(n => n.Lider == namelider))
{
    <td>@peso.Lider</td>
}
    
answered by 12.07.2017 / 00:05
source
3

What you could do is work as a IEnumerable the value of your ViewBag.p to a list of the type of object you have stored:

 @foreach(var peso in ((IEnumerable<Objectives>)ViewBag.p).Where(n => n.Lider == namelider))
 {
     <td>@peso.Lider</td>
 }
    
answered by 11.07.2017 в 23:51