Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a model is empty in Razor View

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

If the model comes up empty, how can I just get it to print "There are no Frames" so that none of the html table gets printed at all, I would think a simple if statement would suffice, but I am new to razor and I wasn't sure how I would go about doing this.

like image 671
anthonypliu Avatar asked May 17 '11 23:05

anthonypliu


1 Answers

Add this to the top of the page:

@using System.Linq

Then replace your code with this block.

@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>
    }
}
like image 75
AnteSim Avatar answered Oct 30 '22 06:10

AnteSim