View condition does not work

1

I'm checking if my ViewBag comes up something

Then I do the following:

@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 it comes to the list of items, it goes through my foreach and does everything as I want, but when it does not have anything, it does not make the condition else I want.

    
asked by anonymous 30.09.2014 / 22:53

2 answers

1

Convert your ViewBag to a strong type before comparing:

@{ 
    var itens = ((IEnumerable<TipoDaLista>)ViewBag.Itens); 
    if (itens != null) 
    {
        ...
    } else {
        ...
    }
}
    
30.09.2014 / 23:32
1

Use Object.ReferenceEquals (null, ViewBag.Items).

The ViewBag and dynamic type, as this type is variable there is no native comparator like string.equals.

    
01.10.2014 / 01:11