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.
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>
}
}
You can also just pass the value to the Viewbag form within the controller and check it in the view like below. 1 - The is the controller -
int numberOfRecords = db.Jobs.ToList().Count(); -
ViewBag.numRecords = numberOfRecords;
ViewBag.ReturnUrl = returnUrl;
return View();
2 - Then just check in the View
@if (ViewBag.numRecords > 0)
精彩评论