Search code examples
c#asp.netrazordisplay-templates

Display for template for an empty list


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.


Solution

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