【问题标题】:If else condition in MVC viewMVC 视图中的 if else 条件
【发布时间】:2019-07-17 19:44:43
【问题描述】:

我正在尝试遍历 if else 条件,如果它们当前显示该项目,如果不显示没有项目的消息。我遇到的问题是无论如何都会显示消息。我做错了什么?

我已经尝试将消息完全置于循环之外并尝试 else if (iscurrent=false) 并且在这两种情况下消息仍然显示。

   <div class="col-md-6">
    <ul>
        @foreach (var item in Model.Items)
        {
            if (item.IsCurrent == true)
            {
                <li>
                    @item.Id
                </li>
            }
            else if (item.IsCurrent == false)
            { 
                @: There is not a current Item at this time. Do you want 
                to
                <a asp-area="Admin" asp-controller="Item" asp- 
            action="CreateItem"> add a Item?</a>
            }
        }




    </ul>

  </div>

我希望只显示设置为 IsCurrent 的项目,当没有项目时只显示消息。

【问题讨论】:

  • 如有任何帮助,我们将不胜感激。

标签: asp.net-mvc-viewmodel


【解决方案1】:

我相信这会更接近你想要的:

<div class="col-md-6">
        <ul>
            @if (Model.Items.Any(x => x.IsCurrent))
            {
                foreach (var item in Model.Items)
                {
                    if (item.IsCurrent)
                    {
                        <li>
                            @item.Id
                        </li>
                    }
                }
            }
            else
            {
                @:There is not a current Item at this time. Do you want to
                <a asp-area="Admin" asp-controller="Item" asp-action="CreateItem">add a Item?</a>
            }
       </ul>
</div>

首先,它使用.Any() 检查任何当前的项目,然后循环通过Model.Items 并显示当前的ID。如果不是,则显示没有当前项目消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    相关资源
    最近更新 更多