View condition does not work

Asked

Viewed 153 times

1

I’m checking if my Viewbag comes something

So I’ll tell you what:

@if (ViewBag.Itens != null)
{
    foreach (var item in ViewBag.Itens)
    {
        <div class="col-md-6">
            <div class="checkbox">
                <label>
                    <input type="checkbox" name="ItensCheck" value="@item.Value" checked="@item.Selected" />
                    @item.Text
                </label>
            </div>
        </div>
    }
}
else
{
    @Html.Raw("Não existe Itens cadastrado.")
}

When he comes to the list of Items, he runs through my foreach and does everything as I want, but when he has nothing, he does not make the condition.

2 answers

1


Convert your Viewbag to a strong type before comparing:

@{ 
    var itens = ((IEnumerable<TipoDaLista>)ViewBag.Itens); 
    if (itens != null) 
    {
        ...
    } else {
        ...
    }
}
  • It still doesn’t work, I send a List<Selectlistitem> and yet, I can’t get Else to return that message

  • @Rod already tried to inspect the ViewBag.Itens in Debug?

  • It does not come null, but with Count()>0 also does not work..

  • Gypsy, I created a variable @ { var Items = .. and then I made the conditions and loop on it and it worked, just edit your answer so I can mark, after all, without your answer I wouldn’t have solved

  • @Rod edited the reply. Thank you.

1

Use Object.Referenceequals(null, Viewbag.Items).

Viewbag and Dynamic type, as this type is variable there is no native comparator like string.equals.

Browser other questions tagged

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