简体   繁体   中英

If/else is not working properly with using OnInitiliazedAsync in Blazor C#

<div class="form-inline justify-content-center mt-4">
    @if (Products != null && Products.Any())
    {
        @foreach (var product in Products)
        {
            #MyCode
        }
    }
    else 
    {
        <h2>This Store has no Products :)</h2>
    }
</div>
@code
{
    [Parameter]
    public int Id { get; set; }

    public IEnumerable<ProductDTO> Products { get; set; }
    protected override async Task OnInitializedAsync()
    {
        Products = await Store.GetStoreProducts(Id);
    }
}

It first show the else part and then load the if part ( if products are available ). It should work like that if products are available then else part shouldn't be loaded.

Right now you have two states, either the list is null/empty, or the list has at least one entry. The problem is that "null" means the list is loading, but "empty" means the list has loaded and has zero entries. You're considering those the same.

You need to have three states.

  1. The list is loading (value is null)
  2. The list has loaded but has no entries (value is empty list)
  3. The list has loaded and has at least one entry

Simply modify your else to an else if

@if (Products != null && Products.Any())
{
    @foreach (var product in Products)
    {
        #MyCode
    }
}
else if (Products != null && !Products.Any())
{
    <h2>This Store has no Products :)</h2>
}

If Products is null, it won't activate the if or else if, and print nothing. You could add an else afterwards which prints "Loading..." if you wish.


Note, this all works because of the assumption that Store.GetStoreProducts should NEVER return null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM