2012-04-19 61 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>