我试图创建实体框架,它具有一对多的关系ASP.NET MVC应用程序。 对于我已经成功地管理加载项的适当列表下拉控制(在创建视图),但是当我点击创建按钮(在创建视图)页面验证zhcon失败,验证错误消息是The value '1' is invalid.
。
错误
模型
public class Post
{
public int Id { get; set; }
...
public virtual Person Author { get; set; }
}
DataBaseContext
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是一个有效的值。 我缺少的是在这里吗?
提前致谢...