目前我有以下实体:
电影:
public class Movie
{
public int ID { get; set; }
[Required]
public string Title { get; set; }
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
[Required]
public string Genre { get; set; }
[DataType(DataType.Currency), Range(1,100)]
public decimal Price { get; set; }
[StringLength(5)]
public string Rating { get; set; }
[StringLength(200)]
public string comments { get; set; }
public Director director { get; set; }
}
导向器:
[Table("Director")]
public class Director
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required, MaxLength(50)]
[Display(Name = "Name")]
public string name { get; set; }
[Required, MaxLength(50)]
[Display(Name = "Last Name")]
public string lastName { get; set; }
[Required, Range(1,100)]
public int age { get; set; }
[NotMapped]
public string fullName {
get { return this.name + " " + this.lastName; }
}
}
当我访问编辑表单时,我从数据库中的 Director 加载一个 SelectList:
public ActionResult Edit(int id = 0)
{
Movie movie = db.Movies.Find(id);
if (movie == null)
{
return HttpNotFound();
}
ViewBag.Directors = new SelectList(db.Directors.ToList(), "ID", "fullname");
return View(movie);
}
然后我使用@Html.DropDownListFor 以如下形式显示组合框:
<div class="editor-field">
@Html.DropDownListFor(model => model.director, (SelectList)ViewBag.Directors, "Select")
@Html.ValidationMessageFor(model => model.director)
</div>
一切似乎都很好,但是当我选择一个选项并尝试保存表单时,我收到一条验证消息,提示“值 '1' 无效”。其中“1”是导演 ID。
所以,我肯定错过了直接绑定导演的东西。