Как определить, пуста ли модель в Razor View - PullRequest
6 голосов
/ 18 мая 2011
@model IEnumerable<Framely2011.Models.Frames>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th></th>
        <th>
            PictureID
        </th>
        <th>
            UserID
        </th>
    </tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
        <td>
            @item.PictureID
        </td>
        <td>
            @item.UserID
        </td>
        <td>
            Meta 1: @item.MetaTagsObj.Meta1 Meta 2: @item.MetaTagsObj.Meta2 Meta 3: @item.MetaTagsObj.Meta3
        </td>
    </tr>
}

</table>

Если модель выйдет пустой, как я могу просто заставить ее напечатать «Нет фреймов», так что ни одна из таблиц html не будет напечатана вообще, я думаю, что простого оператора if будет достаточно, но я новичок в бритве, и я не был уверен, как мне поступить так.

Ответы [ 2 ]

28 голосов
/ 18 мая 2011

Добавьте это в начало страницы:

@using System.Linq

Затем замените ваш код на этот блок.

@if( !Model.Any() )
{
    <tr><td colspan="4">There are no Frames</td></tr>
}
else
{
    foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
            </td>
            <td>
                @item.PictureID
            </td>
            <td>
                @item.UserID
            </td>
            <td>
                Meta 1: @item.MetaTagsObj.Meta1 Meta 2: @item.MetaTagsObj.Meta2 Meta 3: @item.MetaTagsObj.Meta3
            </td>
        </tr>
    }
}
0 голосов
/ 19 апреля 2017

Вы также можете просто передать значение в форму Viewbag в контроллере и проверить его в представлении, как показано ниже.1 - Контроллер -

int numberOfRecords = db.Jobs.ToList().Count(); - 
ViewBag.numRecords = numberOfRecords;
ViewBag.ReturnUrl = returnUrl;
return View();

2 - Тогда просто проверьте в View

@if (ViewBag.numRecords > 0)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...