【问题标题】:DropDownList Result not being ReturnedDropDownList 结果未返回
【发布时间】: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


    【解决方案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>
    

    【讨论】:

    • 如何将它链接到 ItemType 对象?如果我查看模型生成的数据库,ItemType 表已经有一个外键。
    • 由于命名约定,它应该自动链接。
    • 我测试过了,它没有自动链接,也没有解决问题。
    • 奇怪。也许您可以尝试使用属性来强制执行它。我已经更新了我的答案。
    • 只是一点额外的信息:您实际上不需要将[Required] 属性添加到int 类型的属性。 [Required] 属性只是说“这不能为空”,但由于默认情况下整数不能为空,因此您不需要添加该属性。如果您想要一个可选整数,只需使用 int? 而不是 int。
    猜你喜欢
    • 1970-01-01
    • 2014-06-29
    • 2011-08-09
    • 2010-09-22
    • 2021-05-17
    • 2018-02-19
    • 2015-02-25
    • 2014-02-24
    • 2018-03-23
    相关资源
    最近更新 更多