1
<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.

2
  • @gunr2171 yes I've added the code...it'll be really helpful if you could help. Thanks :) Commented Mar 4, 2022 at 16:58
  • call StateHasChanged() after Product Loaded Commented Mar 4, 2022 at 17:06

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.