我試圖創建具有一對多關係的實體框架的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