如何在Razor View中确定模型是否为空

ant*_*liu 7 c# asp.net razor asp.net-mvc-3

@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>
Run Code Online (Sandbox Code Playgroud)

如果模型出现空白,我怎么才能让它打印出"没有框架",这样根本没有打印出任何html表,我认为一个简单的if声明就足够了,但我是razor和我的新手我不确定如何做到这一点.

小智 29

将其添加到页面顶部:

@using System.Linq
Run Code Online (Sandbox Code Playgroud)

然后用这个块替换你的代码.

@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>
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我将@using System.Linq添加到razor视图页面的顶部,然后添加@if(Model.Any()){@ Html.DropDownListFor(m => m.SelectedSuffix,new SelectList(Model.Suffix,"Value","文本",Model.SuffixDBValue","")}但是我得到错误'不包含'Any'的定义,没有扩展方法'Any'接受类型的第一个参数..' (8认同)