2017-04-04 40 views
1

對不起,我真的不知道如何標題。 我有一個顯示公告的網頁。我似乎無法弄清楚的是,是否有任何公告,如果有顯示說「沒有公告」。如何查看View是否收到沒有結果

我試過的東西,如:

if(db.Announcements.toArray().length == 0){ 
    return View(null); 
} 

,但不起作用。我在哪裏處理這些事情?視圖/控制器?

查看:

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

控制器:

// GET: Announcements 
    public ActionResult Index() 
    { 

     return View(db.Announcements.ToList()); 
    } 
+0

'if(Model.Any()){//顯示通告} else {//顯示空消息}' – haim770

+0

@ haim770 Brillaint,謝謝。如果你回答我會標記爲正確的。 – user3042332

回答

1

由於您的模型定義爲IEnumerable<Announcement>,你可以簡單地使用Any()來檢查它是否是空的或不是:

@if (Model.Any()) 
{ 
    // show announcements 
    foreach (var item in Model) 
    { 
     // ... 
    } 
} 
else 
{ 
    // show message when empty 
    <p>No announcements</p> 
} 

MSDN

+0

我會在9分鐘內接受。 – user3042332