正在 MVC 中下拉以绑定到模型

Is getting dropdown in MVC to bind to model

我已经经历过这个问题的许多其他版本,但我的尝试就是行不通。我有一个通知模型。

  public class Notice

  {
    [Key]
    public int NoticeId { get; set; }
    public string UserId { get; set; }
    public string NoticeTitle { get; set; }
    public bool Public { get; set; }
    public NoticeType Type { get; set; }

  }

带有 NoticeType Table

  public class NoticeType
  {
    [Key]
    public int NoticeTypeId { get; set; }
    public string Type { get; set; }
  }

然后我在我的 Get 中填充 select 列表。

  public ActionResult Create()
  {
    List<NoticeType> _noticeTypes = db.NoticeTypes.ToList();
    SelectList noticeTypes = new SelectList(_noticeTypes, "NoticeTypeId", "Type");
  
    ViewBag.NoticeTypes = noticeTypes;
    return View();
  }

并且下拉列表中填充了我的 table 数据。

@Html.DropDownListFor(model => model.Type, ViewBag.NoticeTypes as SelectList, new { @class = "form-control" })

但是,类型值没有传递到我的 Create post。

拜托,谁能解释一下原因。

谢谢。

修复 class

public class Notice

  {
    [Key]
    public int NoticeId { get; set; }
    public string UserId { get; set; }
    public string NoticeTitle { get; set; }
    public bool Public { get; set; }

     public  int NoticeTypeId  { get; set; }
    public virtual NoticeType NoticeType  { get; set; }

  }

并查看

@Html.DropDownListFor(model => model.NoticeTypeId, ViewBag.NoticeTypes as SelectList, new { @class = "form-control" })