[英]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 ).它首先显示 else 部分,然后加载 if 部分(如果产品可用)。 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.
问题是“null”表示列表正在加载,而“empty”表示列表已加载且条目为零。 You're considering those the same.
你正在考虑那些相同的。
You need to have three states.你需要有三个状态。
Simply modify your else
to an else if
只需将您的
else
修改为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.如果
Products
是 null,它不会激活 if 或 else if,并且不打印任何内容。 You could add an else
afterwards which prints "Loading..." if you wish.如果您愿意,您可以在之后添加一个打印“正在加载...”的
else
。
Note, this all works because of the assumption that Store.GetStoreProducts
should NEVER return null.请注意,这一切都有效,因为假设
Store.GetStoreProducts
永远不会返回 null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.