【发布时间】:2014-07-10 23:29:43
【问题描述】:
我有一个项目(如下),其中有类别和产品。每个类别都有多个产品,从模型中可以看出,类别 ID 被引用为外键。我想要做的是让每个类别显示为一个 div,相应的产品显示在下面的无序列表中。使用我拥有的代码,我不断得到一个 div 和一个产品,每个产品的类别都重复。
我已经搜索和搜索,但似乎无法找到解决方案。我哪里错了?
视图模型
使用系统; 使用 System.Collections.Generic; 使用 System.ComponentModel.DataAnnotations; 使用 System.ComponentModel.DataAnnotations.Schema; 使用 System.Linq; 使用 System.Web; 使用 System.Web.Mvc;namespace WebApplication1.Web.Models
{
public class Category
{
public int CategoryID { get; set; }
[Required, Display(Name = "Category Name")]
public string CategoryName { get; set; }
public bool IsDisplayedInMainMenu { get; set; }
}
public class Product
{
public int ProductID { get; set; }
public int CategoryID { get; set; }
[ForeignKey("CategoryID")]
[Display(Name = "Category Name")]
public Category CategoryName { get; set; }
[Required, Display(Name = "Product Name")]
public string ProductName { get; set; }
[Required, Display(Name = "Product Description")]
[DataType(DataType.MultilineText)]
public string ProductDescription { get; set; }
}
}
产品控制器
namespace WebApplication1.Controllers
{
public class ProductsController : Controller
{
private ServiceContext db = new ServiceContext();
// GET: Products
public ActionResult Index()
{
var products = db.Products.Include(p => p.CategoryName);
return View(products.ToList());
}
}
}
查看
model IEnumerable
@{
ViewBag.Title = "Products";
}
<h2>@ViewBag.Title</h2>
<div class="row">
@foreach (var item in Model)
{
<div class="col-md-3">
<h4><strong>@item.CategoryName.CategoryName</strong></h4>
<ul class="list-unstyled">
@if (item.ProductName.Any())
{
<li>
@item.ProductName
</li>
}
</ul>
</div>
}
</div>
产品
木材 2×4
木材 1 X 4
木材 胶合板
电动工具 钻孔
电动工具 圆锯
花园 柠檬树
花园 橘子树
紧固件 干墙螺丝
紧固件 甲板螺丝
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-5.1