【发布时间】:2012-07-18 20:23:49
【问题描述】:
我正在尝试创建一个 ItemType 来自另一个表的项目。我无法从 Create 页面取回实际的 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。
我需要做什么才能让它工作?
【问题讨论】:
标签: asp.net-mvc-3 c#-4.0 entity-framework-4.1