0

I have a view with a model, this model contains a list of items.

<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">@Resources.StatusMessage</h3>
    </div>
    @for (int i = 0; i < Model.StatusMessages.Count; i++)
    {
        @Html.DisplayFor(m => m.StatusMessages[i])
    }
    <div class="panel-footer">
        @Html.ActionLink(Resources.AddStatusMessage, "AddStatusMessage", new {Id = Model.Id})
    </div>
</div>

This List is displayed using a DisplayFor template. The template is based on the item in the list and the displayFor simply loops over it.

The problem is that when the list is empty i'd like to have a placeholder string that says "No status messages".

I'm looking for a way to add this placeholder preferably using the already existing display for template.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Axel Bouttelgier
  • 173
  • 1
  • 12

3 Answers3

1

If you using Templates you can do it simplier:

<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">@Resources.StatusMessage</h3>
    </div>
    @if(Model.StatusMessages != null && Model.StatusMessages.Any())
    {
        @Html.DisplayFor(m => m.StatusMessages)
    }
    else
    {
        <p>No status messages</p>
    }
    <div class="panel-footer">
        @Html.ActionLink(Resources.AddStatusMessage, "AddStatusMessage", new {Id = Model.Id})
    </div>
</div>

You don't need loop becouse Razor templates iterate collection for you.

teo van kot
  • 12,350
  • 10
  • 38
  • 70
1

have you tried the bellow

<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">@Resources.StatusMessage</h3>
    </div>
    @if(!Model.StatusMessages.Any()){@Html.DisplayFor(m => "Your string message here")}
    @for (int i = 0; i < Model.StatusMessages.Count; i++)
    {
        @Html.DisplayFor(m => m.StatusMessages[i])
    }
    <div class="panel-footer">
        @Html.ActionLink(Resources.AddStatusMessage, "AddStatusMessage", new {Id = Model.Id})
    </div>
</div>`
Muhammed Shevil KP
  • 1,404
  • 1
  • 16
  • 21
  • this seems like it'll do the trick. Altough i'm still strugling to find the border between logic that is allowed in the view and logic that should strictly be in the controller – Axel Bouttelgier Feb 10 '17 at 08:32
1

A simple If would do the trick:

<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">@Resources.StatusMessage</h3>
    </div>
    @{
      if(Model.StatusMessages != null)
      {
        for (int i = 0; i < Model.StatusMessages.Count; i++)
        {
        @Html.DisplayFor(m => m.StatusMessages[i])
        }
      }
      else
      {
       @Html.Display("No Status")
      }
     }

    <div class="panel-footer">
        @Html.ActionLink(Resources.AddStatusMessage, "AddStatusMessage", new {Id = Model.Id})
    </div>
</div>
Masoud Andalibi
  • 3,168
  • 5
  • 18
  • 44