2012-04-19 37 views
1

我在視圖中遇到了從不同實體中提取數據的問題。基本上我有一個橋接實體CategoryProduct,它將類別和產品數據放在一起。我最終想要展示的是產品列表以及每種產品的類別。然而,我完全停留在如何使最後一部分 - 顯示類別 - 發生。ASP.NET MVC3 Razor在模型中查詢(foreach在foreach中)

下面是我的模型的代碼 -

public class Product 
    { 
     public int ProductId { get; set; } 
     public string Title { get; set; } 
     public virtual ICollection<CategoryProduct> CategoryProducts { get; set; } 
    } 

    public class CategoryProduct 
    { 
     public int CategoryProductID { get; set; } 
     public int CategoryId { get; set; } 
     public int ProductId { get; set; } 
     public virtual Product Product { get; set; } 
     public virtual Category Category { get; set; } 
    } 

    public class Category 
    { 
     public int CategoryId { get; set; } 
     public string Title { get; set; } 
     public virtual ICollection<CategoryProduct> CategoryProducts { get; set; } 
    } 

我的控制器是非常簡單的,它只是推,彌補實體查看:

public ActionResult Index() 
{ 
    return View(db.CategoryProducts.ToList()); 
} 

最後我的視圖顯示產品和分類,但權現在它只是爲同一產品創建額外的行,如果它具有不同的類別,例如產品1:類別1,產品1:類別2等。而當我想要得到的產品1:1類,2類

@model IEnumerable<ProductsCode.Models.CategoryProduct> 
<h2>Index</h2> 
<table> 
    <tr> 
     <th>Title</th> 
     <th>Category</th> 
    </tr> 

@foreach (var item in Model) { 
    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.Product.Title) 
     </td> 
     <td> 
      @foreach (var categories in item) 
      { 
      @Html.DisplayFor(modelItem => item.Why.Title)    
      } 
     </td> 
    </tr> 
} 
</table> 

錯誤出在:編譯器錯誤消息:CS1579:foreach語句無法在類型「ProductsCode.Models.CategoryProduct」的變量操作,因爲'ProductsCode.Models.CategoryProduct'不包含'GetEnumerator'的公共定義

編輯:添加了其他foreach循環和錯誤。

+1

我沒有看到一個'foreach'內'foreach'遏制。 – 2012-04-19 14:12:10

+0

@KirkWoll這就是我在foreach內運行foreach的問題 - 我得到一個錯誤,說它不是IEnumerable – firedrawndagger 2012-04-19 14:14:18

+0

它在哪裏抱怨它不是'IEnumerable'? *什麼是*不是'IEnumerable'? – 2012-04-19 14:18:25

回答

3

爲什麼你就不能更改視圖模型是這樣的

public class MyProduct 
    { 
     public int ProductId { get; set; } 
     public string Title { get; set; } 
     public virtual ICollection<Category> CategoryList { get; set; } 
    } 

,並查看

@model IEnumerable<ProductsCode.Models.MyProduct> 
<h2>Index</h2> 
<table> 
    <tr> 
     <th>Product</th> 
     @Html.DisplayFor(modelItem => item.ProductId) 
     <th>Categories for Product</th> 
    </tr> 

@foreach (var item in Model.CategoryList) { 
    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.Title) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.CategoryId) 
     </td> 
    </tr> 
} 
</table>