ASP.NET MVC3 Razor 模型内部查询(foreach 内 foreach)

2024-04-14

我在视图中遇到从不同实体提取数据的问题。基本上我有一个桥接实体 CategoryProduct 将类别和产品数据汇集在一起​​。我想要最终显示的是产品列表以及每个产品的类别。然而,我完全不知道如何实现最后一部分 - 显示类别 - 发生。

这是我的模型的代码 -

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 循环和错误。


为什么你不能像这样改变视图模型

 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.NET MVC3 Razor 模型内部查询(foreach 内 foreach) 的相关文章

随机推荐