gpt4 book ai didi

asp.net-mvc-3 - DropDownList 结果未返回

转载 作者:行者123 更新时间:2023-12-02 20:34:09 25 4
gpt4 key购买 nike

我正在尝试创建一个具有来自另一个表的 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 View 中我尝试过:

<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 的 stub 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,即使它应该如此。

我需要做什么才能让它发挥作用?

最佳答案

您应该将属性 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>

关于asp.net-mvc-3 - DropDownList 结果未返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11549667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com