You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用C#(HTML Razor):值为null时如何不显示指定HTML元素?

问题解决

你的代码仅判断了ContactPerson不为null,但如果它是一个空集合(无任何联系人数据),依然会渲染出带有「Contact Details」标题的卡片。要实现空数据时完全不显示卡片,需要同时判断集合是否包含有效元素:

修改后的代码如下:

@if (Model.Item.Fields.ContactPerson != null && Model.Item.Fields.ContactPerson.Any())
{
  <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="mailto:@person.Fields.Email"><i class="bi bi-envelope-fill"></i> Email @person.Fields.Name</a>
        </p>
      }
    </div>
  </div>
}

额外补充:你的邮箱链接缺少mailto:协议,已在代码中补上,确保点击能正确唤起邮件客户端。

内容的提问来源于stack exchange,提问作者Millhorn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 03:46:07