Search code examples
c#razor

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.

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>
  }

Solution

  • 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)