【发布时间】:2014-07-14 21:07:27
【问题描述】:
我一定是做错了什么,搜索了谷歌和这个表格,但我找不到。
我有以下类“产品”,由 EF 生成,代表数据库表“产品”:
public partial class product
{
public product()
{
this.category = new HashSet<category>();
}
public string name { get; set; }
public string description { get; set; }
public decimal price { get; set; }
public virtual ICollection<category> category { get; set; }
}
我还有另一个类 'category',也是用 EF 生成的,代表一个数据库表 'category':
public partial class category
{
public category()
{
this.product = new HashSet<product>();
}
public string name { get; set; }
public virtual ICollection<product> product { get; set; }
}
数据库中的两个表具有多对多关系,通过一个名为 product2category 的链接表实现,该链接表包含 category_name 和 product_name 的组合 PK。 category_name 是 [categroy.name] 的外键。 product_name 是[product.name] 的外键(category.name 是category 表中的PK,product.name 是product 表中的PK)我先用database,没有EF 生成的class 名为product2category。
我有一个动作方法:
public ActionResult Edit(string id = null)
{
product product = db.product.Find(id);
if (product == null)
{
return HttpNotFound();
}
IEnumerable<SelectListItem> categoryList = db.category
.ToList()
.Select(o => new SelectListItem() {
Value = o.name,
Text = o.name,
Selected = product.category.FirstOrDefault().name == o.name
}
);
ViewBag.categoryList = categoryList;
return View(product);
}
我插入了一个断点并调查了 categoryList 属性的值。它有 3 个结果(展开结果视图时):
假,“足球”,“足球”
假,“棒球”,“棒球”
真,“网球”,“网球”
我有以下视图(为简洁起见,省略了一些 HTML)
<div class="editor-label">
@Html.LabelFor(model => model.category)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.category, (IEnumerable<SelectListItem>)ViewBag.categoryList)
@Html.ValidationMessageFor(model => model.category)
</div>
视图生成 html 下拉列表,但未选择“网球”值。或者说,它没有在 Tennis 选项标记处设置 selected="selected" 属性(可以肯定的是,我还在视图中插入了一个断点,以调查 ViewBag.categoryList 属性,但它给出的结果与控制器):
<div class="editor-label">
<label for="category">category</label>
</div>
<div class="editor-field">
<select id="category" name="category">
<option value="Baseball">Baseball</option>
<option value="Football">Football</option>
<option value="Tennis">Tennis</option>
</select>
<span class="field-validation-valid" data-valmsg-for="category" data-valmsg-replace="true"></span>
</div>
我找不到为什么它没有默认选择网球选项。
第二个问题:
我也无法编辑或创建产品,因为 html select 元素的 name 和 id 属性的值。该值设置为“类别”,但必须类似于 category.name 是我相信的。
【问题讨论】:
-
你试过用括号括起来吗
Selected = (product.category.FirstOrDefault().name == o.name)
标签: entity-framework asp.net-mvc-4