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 seems empty, how can I simply print βNo Framesβ so that none of the html tables prints at all, I would think that a simple if would suffice, but I'm new to razor and I'm not I was sure how I would do it.
Add this at the top of the page:
@using System.Linq Then replace your code with this block.
@if( !Model.Any() ) { <tr><td>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 simply pass the value to the Viewbag form in the controller and check it in the view, as shown below. 1 - 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)