我正在尝试创建一个具有来自另一个表的ItemType的Item。我无法从“创建”页面返回实际的Type对象。这是我尝试过的代码:
型号:
public class ItemType {
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Item> Item{ get; set; }
}
public class Item {
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ItemType ItemType { get; set; }
}
在ItemController中,这是我的创建代码:
public ActionResult Create() {
var itemTypeRepo = new ItemTypeRepository(context);
ViewBag.ItemTypes = new SelectList(itemTypeRepo.GetAll(), "ID", "Name");
return View();
}
[HttpPost]
public ActionResult Create(Item item) {
if (ModelState.IsValid) {
context.Items.Add(item);
context.SaveChanges();
return RedirectToAction("Index");
}
return View(item);
}
在我的Create.cshtml视图中,我尝试过:
<div class="editor-field">
@Html.DropDownList("ItemType", String.Empty)
@Html.ValidationMessageFor(model => model.ItemType)
</div>
这根本不返回任何值并抛出错误“值'X'无效。”其中X是我选择的ItemType的ID。 和
<div class="editor-field">
@Html.DropDownListFor(x => x.ItemType.Id, (SelectList)ViewBag.ItemType)
@Html.ValidationMessageFor(model => model.ItemType)
</div>
这将创建一个具有正确ID的存根ItemType对象,但由于该对象未完全加载,因此不会将其插入数据库。如果我查看ModelState对象,我发现ItemType对象中缺少Name字段的错误。
我还尝试使用第二个.cshtml代码并添加此代码来解决问题:
public ActionResult Create(Item item) {
item.ItemType = context.ItemTypes.Find(item.ItemType.Id);
if (ModelState.IsValid)
这不会将ModelState.IsValid的值从false更改为false。
我需要做些什么才能让它发挥作用?
答案 0 :(得分:1)
您应该将属性ItemTypeId添加到Item实体,以便它充当外键。
public class Item
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public int ItemTypeId { get; set; }
[ForeignKey("ItemTypeId")]
public virtual ItemType ItemType { get; set; }
}
然后,您可以将该属性用于下拉列表:
<div class="editor-field">
@Html.DropDownListFor(x => x.ItemTypeId, (SelectList)ViewBag.ItemType)
@Html.ValidationMessageFor(model => model.ItemType)
</div>