<div >
@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.
CodePudding user response:
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.
- The list is loading (value is null)
- The list has loaded but has no entries (value is empty list)
- 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.
CodePudding user response:
This is how you should code:
@if (Products == null)
{
@*Display Loading... message as long as the Task is not
comleted*@
<p><em>Loading...</em></p>
}
else if (Products != null && !Products.Any())
{
@*Display message after Task is completed with zero
objects returned*@
<h2>This Store has no Products :)</h2>
}
else
{
@*Display the returned objects*@
#MyCode
}