英文:
Using C# (HTML Razor), how can I not display specific HTML element if the returned value is null?
问题
If ContactPerson is empty, then the card should not display. If it returns true, then display.
然而,我认为我漏掉了一些东西,因为当我返回一个空值时,它仍然显示带有标题“联系方式”的卡。
以下是我的代码:
@if (Model.Item.Fields.ContactPerson != null)
{
<div class="notice__card card mb-3">
<div class="card-body">
<h3 class="notice__card--contact">联系方式</h3>
@foreach (var person in Model.Item.Fields.ContactPerson)
{
<p class="card-text">
<span>@person.Fields.Name</span>
<a href="tel:@person.Fields.Phone"><i class="bi bi-telephone-fill"></i> @person.Fields.Phone</a>
<a href="@person.Fields.Email"><i class="bi bi-envelope-fill"></i> 邮件 @person.Fields.Name</a>
</p>
}
</div>
</div>
}
英文:
If ContactPerson is empty, then the card should not display. If it returns true, then display.
However, I think I'm missing something because when I return a null value, it's still displaying the card with the title "Contact Details"
Here's my code:
@if (Model.Item.Fields.ContactPerson != null)
{
<div class="notice__card card mb-3">
<div class="card-body">
<h3 class="notice__card--contact">Contact Details</h3>
@foreach (var person in Model.Item.Fields.ContactPerson)
{
<p class="card-text">
<span>@person.Fields.Name</span>
<a href="tel:@person.Fields.Phone"><i class="bi bi-telephone-fill"></i> @person.Fields.Phone</a>
<a href="@person.Fields.Email"><i class="bi bi-envelope-fill"></i> Email @person.Fields.Name</a>
</p>
}
</div>
</div>
}
答案1
得分: 4
这行代码:
@foreach (var person in Model.Item.Fields.ContactPerson)
表明(名称误导的)属性 ContactPerson
是一个集合。所以,如果这个条件成立:
@if (Model.Item.Fields.ContactPerson != null)
而这个循环却从不执行:
@foreach (var person in Model.Item.Fields.ContactPerson)
那么你所拥有的不是 null
,而是一个空的集合。从概念上来说... 一个空的盒子仍然是一个盒子。
看起来你想要测试是否为 null
且是否为空集合。例如:
@if (Model.Item.Fields.ContactPerson != null && Model.Item.Fields.ContactPerson.Count() > 0)
英文:
This line:
@foreach (var person in Model.Item.Fields.ContactPerson)
Suggests that the (misleadingly named) property ContactPerson
is a collection. So if this is true
:
@if (Model.Item.Fields.ContactPerson != null)
And this never iterates:
@foreach (var person in Model.Item.Fields.ContactPerson)
Then what you have is not null
, but an empty collection. To describe it conceptually... An empty box is still a box.
It sounds like you want to test for null
and an empty collection. For example:
@if (Model.Item.Fields.ContactPerson != null && Model.Item.Fields.ContactPerson.Count() > 0)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论