我正在尝试使用具有一对多关系的实体框架创建 ASP.NET MVC 应用程序。为此,我已成功地将适当的项目列表加载到下拉控件(在创建视图中),但是当我单击创建按钮(在创建视图中)页面验证失败时,验证错误消息为The value '1' is invalid.
.
错误
模型
public class Post
{
public int Id { get; set; }
...
public virtual Person Author { get; set; }
}
数据库上下文
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Post>()
.HasOptional(p => p.Author);
}
控制器
public ActionResult Create()
{
PopulateAuthorDropDownList();
return View();
}
[HttpPost]
public ActionResult Create(Post post)
{
if (ModelState.IsValid)
{
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Index");
}
PopulateAuthorDropDownList(post.Author);
return View(post);
}
private void PopulateAuthorDropDownList(object selectedPerson = null)
{
var personQuery = from d in db.People
orderby d.Name
select d;
ViewBag.Author = new SelectList(personQuery, "Id", "Name", selectedPerson);
}
看法
<div class="editor-label">
@Html.LabelFor(model => model.Author)
</div>
<div class="editor-field">
@Html.DropDownList("Author", String.Empty)
@Html.ValidationMessageFor(model => model.Author)
</div>
当我检查数据库中的作者表时,有 ID 为 1 的记录,所以我猜 1 是一个有效值。我在这里想念什么?
提前致谢...