【发布时间】:2013-04-05 02:28:41
【问题描述】:
大编辑:我已经编辑了我的完整帖子,答案是我在 Von V 和 Johannes 的帮助下提出的,非常感谢你们!!!!
我一直在尝试在我的索引视图中的 foreach 循环内执行一个 foreach 循环,以在手风琴中显示我的产品。让我告诉你我是如何做到这一点的。
这是我的模型:
public class Product
{
[Key]
public int ID { get; set; }
public int CategoryID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Path { get; set; }
public virtual Category Category { get; set; }
}
public class Category
{
[Key]
public int CategoryID { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
这是一个one-one一对多的关系,一个产品只有一个类别,但一个类别有很多产品。
在我看来,这是我想要做的事情:
@model IEnumerable<MyPersonalProject.Models.Product>
<div id="accordion1" style="text-align:justify">
@foreach (var category in ViewBag.Categories)
{
<h3><u>@category.Name</u></h3>
<div>
@foreach (var product in Model)
{
if (product.CategoryID == category.CategoryID)
{
<table cellpadding="5" cellspacing"5" style="border:1px solid black; width:100%;background-color:White;">
<thead>
<tr>
<th style="background-color:black; color:white;">
@product.Title
@if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
{
@Html.Raw(" - ")
@Html.ActionLink("Edit", "Edit", new { id = product.ID }, new { style = "background-color:black; color:white !important;" })
}
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="background-color:White;">
@product.Description
</td>
</tr>
</tbody>
</table>
}
}
</div>
}
</div>
我不太确定这是正确的做法,但这正是我想要做的。对于每个类别,将该类别的所有产品放在一个折叠标签中。
- 类别 1
- 产品1
- 产品 3
- 2 类
- 产品 2
- 产品 4
- 第 3 类
- 产品5
在这里,我将为 我的一对一 一对多(感谢 Brian P)关系添加映射:
public class MyPersonalProjectContext : DbContext
{
public DbSet<Product> Product { get; set; }
public DbSet<Category> Category { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Product>();
modelBuilder.Entity<Category>();
}
}
我还将添加我的控制器,以便您了解我是如何做到的:
public ActionResult Index()
{
ViewBag.Categories = db.Category.OrderBy(c => c.Name).ToList();
return View(db.Product.Include(c => c.Category).ToList());
}
大编辑:我已经编辑了我的完整帖子,答案是我在 Von V 和 Johannes 的帮助下提出的,非常感谢你们!!!!
【问题讨论】:
-
如果存在一对一的关系,为什么 Product 类中有一个 ICollection
?你的控制器动作是什么样的?传递给视图的模型是什么? -
我有 ICollection
的原因是因为有时我需要获取此模型的 CatogoryID 或名称。就像在这里一样,我想在我的手风琴 上显示类别名称。我做得不对吗?
-
你们的关系不是一对一,而是多对一,你只是倒着想。 1 个类别有很多产品。
-
@BrianP 我认为你是对的......我倒是想了一下。现在,为什么我无法做到这一点是有道理的
标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-4