我试图创建具有一对多关系的实体框架的ASP.NET MVC应用程序。为此,我已成功设法将适当的项目列表加载到下拉控件(在“创建”视图中),但是当我单击“创建”按钮(在“创建”视图中)页面验证为faild时,验证错误消息为The value '1' is invalid.
。ASP.NET MVC页面验证失败(值无效)
错误
模型
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是一个有效的值。我在这里错过了什么?
在此先感谢...
你在哪里得到这个错误?这是一个例外吗?它是无效的ModelState?你的模型类是否有DataAnnotation属性? – Jan
@Jan Page.IsValid失败,消息显示在视图“ValidationMessageFor”字段中。 – Nalaka526