如何向父模型显示 link 子模型列表的编辑器?

How do I display an editor for a list of child models to link to the parent model?

我通过 EF 设置了以下模型关系:

public class Purpose
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Purpose> Purposes { get; set; }
}

我的目的是预先在数据库中定义的,一个Item可以有很多Purposes(想想它们几乎就像"tags")。用户无法在 Item 编辑器中添加新的 Purpose,他们只能从已有的编辑器中进行选择。

我是 MVC 的新手,正在尝试为我的 Item class 创建 CRUD 操作。我搭建了我的 EF 模型,所以我掌握了基础知识(例如,它允许我编辑 Name 属性,因为那是一个简单的 属性),但它没有搭建更复杂的关系.

我正在寻找的是,在“编辑”视图中,一个复选框列表列出了数据库中的每个 Purpose,当一个或多个被选中时,它会将它们添加到 List<Purpose>关系就Itemclass。这是我 Item.cshtml 视图中的内容:

@Html.EditorFor(model => model.Purposes)

我已经创建了一个 Views/Shared/EditorTemplates/Purpose.cshtml 编辑器模板,但我不确定我应该在其中放入什么,或者这最终将如何 link 到我的主要 Item 查看。

视图模型是您的朋友。包含一个布尔值 属性 以指示选定的 Purpose 个对象

public class PurposeVM
{
  public int Id { get; set; }
  public string Name { get; set; }
  public bool IsSelected { get; set; }
}

public class ItemVM
{
  public int Id { get; set; } // only required for an edit view model
  [Required]
  public string Name { get; set; }
  public List<PurposeVM> Purposes { get; set; }

}

控制器

public ActionResult Create()
{
  ItemVM model = new ItemVM();
  // map all purposes from database, for example
  model.Purposes = db.Purposes.Select(p => new PurposeVM()
  {
    Id = p.Id,
    Name = p.Name
  });
  return View(model);
}

[HttpPost]
public ActionResult Create(ItemVM model)
{
}

查看

@model ItemVM
@using(Html.BeinForm())
{
  @Html.LabelFor(m => m.Name)
  @Html.TextBoxFor(m => m.Name)
  @Html.ValidationMessageFor(m => m.Name)
  for(int i = 0; i < Model.Purposes.Count;i++)
  {
    @Html.CheckBoxFor(m => m.Purposes[i].IsSelected)
    @Html.LabelFor(m => m.Purposes[i].IsSelected, Model.Purposes[i].Name)
    @Html.HiddenFor(m => m.Purposes[i].Id) // plus hidden input for name if you want to post that as well
  }
  <input type="submit" />
}