Reputation: 81
Sorry I didn't really know how to title this. I have a webpage that displays announcements. What I cant seemed to figure out is whether there are any announcements, if there are display saying "There are no announcements".
I've tried stuff like:
if(db.Announcements.toArray().length == 0){
return View(null);
}
but that doesn't work. Where do I deal with things like these? View/Controller?
View:
@model IEnumerable<Remake.Models.Announcement>
@{
ViewBag.Title = "Announcements";
}
<h2>Announcements</h2>
@if (User.Identity.IsAuthenticated)
{ <p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
<b> @Html.DisplayNameFor(model => model.Title)</b>
</th>
<th>
@Html.DisplayNameFor(model => model.Content)
</th>
<th width="10%">
@Html.DisplayName("Date")
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
<b> @Html.DisplayFor(modelItem => item.Title)</b>
</td>
<td>
@Html.DisplayFor(modelItem => item.Content)
</td>
<td>
<b>@Html.DisplayFor(modelItem => item.PostDate)</b>
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.AnnouncementId }) |
@Html.ActionLink("Comments", "Details", new { id = item.AnnouncementId }) |
@Html.ActionLink("Delete", "Delete", new { id = item.AnnouncementId })
</td>
</tr>
}
</table>
}
else
{
<p>Please sign in to create an Announcement</p>
}
Controller:
// GET: Announcements
public ActionResult Index()
{
return View(db.Announcements.ToList());
}
Upvotes: 1
Views: 209
Reputation: 49105
Since your model is defined as IEnumerable<Announcement>
, you can simply use Any()
to check whether it's empty or not:
@if (Model.Any())
{
// show announcements
foreach (var item in Model)
{
// ...
}
}
else
{
// show message when empty
<p>No announcements</p>
}
See MSDN
Upvotes: 1