Question

I'm trying to compare datas from two different ViewBags which contain each of them a list of objects and if two objects are the same I would like to display a checkbox checked and if not, a checkbox not checked. I've tried that:

 @for (int i = 0; i < ViewBag.Fonctions.Count(); i++)
        {
               for (int y = 0; y < ViewBag.FonctionsContact.Count(); y++)
                   {
                       if (ViewBag.Fonctions[i] == ViewBag.FonctionsContact[y])
                       {
                           <input type="checkbox" value="@ViewBag.Fonctions[i].IdFonction" checked/>
                        }
                         else
                         {
                           <input type="checkbox" value="@ViewBag.Fonctions[i].IdFonction"/>
                         }
                    }
        }

But it shows me an error RuntimeBindingException. Maybe there are different ways to do that... Somebody has an idea ?

Was it helpful?

Solution

You cannot call extension methods (.Count() in your case) on dynamic variables. This is a limitation of .NET that has nothing to do with ASP.NET MVC.

So you will have to use the corresponding property. For example if those are arrays use .Length and if they are collections use .Count

@for (int i = 0; i < ViewBag.Fonctions.Count; i++)
{
    for (int y = 0; y < ViewBag.FonctionsContact.Count; y++)
    {
        if (ViewBag.Fonctions[i] == ViewBag.FonctionsContact[y])
        {
            <input type="checkbox" value="@ViewBag.Fonctions[i].IdFonction" checked/>
        }
        else
        {
            <input type="checkbox" value="@ViewBag.Fonctions[i].IdFonction"/>
        }
    }
}

Of course this is just some hacky stuff, the correct solution to this problem is obviously to get rid of ViewBag and use strongly typed view model where you wouldn't have had such problems at all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top