2016-12-19 35 views
1

我試圖在控制器中使用它來獲取組所有類別,並統計每個類別的總數。MVC ASP.NET在顯示使用Razor代碼的結果中的顯示組計數

 //Report 
     public ActionResult Report() 
     { 
      var reports = 
     db.Product 
     .GroupBy(r => r.CategoryName) 
     .Select(r => new { Name = r.Key, Count = r.Count() }); 
      return View(reports); 
     } 

如何在View中訪問和顯示Count和CategoryName?我想是這樣顯示的:

CategoryName  Count 
P1     2 
P2     3 
P3     4 
P4     2 

我在Report.cshtml這樣的事情,但它不工作:

@model IEnumerable<SiteKitBMI.Models.Product> 
@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

<table class="table"> 
    <tr> 
     <th> 
      @Html.DisplayNameFor(model => model.Name) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.Count) 
     </th> 
     <th></th> 
    </tr> 

@foreach (var item in Model) { 
    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.Name) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.Count) 
     </td> 
    </tr> 
} 

</table> 

任何人都可以照一些輕到這個? 任何幫助,非常感謝。

+0

它怎麼不起作用?錯誤?空屏幕? – DarkKnight

+0

您不會返回'IEnumerable '到視圖(您的代碼將引發異常)。創建一個包含「Name」和「Count」屬性的視圖模型(稱爲'ProductVM'),並將您的查詢投影到它中, - 選擇r => new ProductVM {...},然後使用@model IEnumerable ' –

+0

首先,您需要創建列表並使用視圖包在視圖中發送,然後通過類型轉換來獲取它,然後您可以在foreach循環中使用它。 –

回答

0

您的控制器查詢正在將一個匿名對象的集合返回到期望集合Product並將在那裏拋出的視圖傳遞到字典中的模型項是類型...但該字典需要模型項的類型...異常。

由於Product不包含財產Count,你需要創建一個視圖模型來表示要在視圖中顯示

public class ProductQuantitiesVM 
{ 
    public string Name { get; set; } 
    public int Count { get; set; } 
} 

,然後投射查詢到的ProductQuantitiesVM

收集什麼
var reports = db.Product.GroupBy(r => r.CategoryName) 
    .Select(r => new ProductQuantitiesVM() 
    { 
     Name = r.Key, 
     Count = r.Count() 
    }); 
return View(reports); 

最後,改變視圖使用ProductQuantitiesVM

@model IEnumerable<ProductQuantitiesVM> 
.... 
+0

我最初有問題從iqueryable執行toList(),錯誤表示不支持。所以我改變了一點。主要基礎是CategoryName屬性包含依賴於來自另一個屬性的值的條件語句。 – Jase

+0

但是,我現在已經使用了ProductQuantitiesVM視圖模型類方法,並修復了這個問題,它的工作完美:) – Jase