ASP.NET MVC页面验证失败(该值是无效的。) [英] ASP.NET MVC Page Validation Fails (The value is invalid.)
问题描述
我试图创建实体框架,它具有一对多的关系ASP.NET MVC应用程序。对于我已经成功地管理加载项的适当列表下拉控件(在创建视图),但是当我点击创建按钮(在创建视图)页面验证faild,验证错误消息是值'1'是无效的。
。
I'm trying to create ASP.NET MVC Application with Entity Framework, which has One to Many relationship. For that I have successfully managed to load the appropriate list of items to a dropdown control (in Create view), But when I click the Create button (in Create view) page validation is faild, validation error message is 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>
当我在数据库中查询Author表有记录ID为1,所以我猜1是一个有效的价值。缺少什么我在这里?
When I check Author table in database there is Record with Id 1, so I guess 1 is a valid value. What am I missing here?
在此先感谢...
推荐答案
设法解决这个通过
改变型号到
public class Post
{
public int Id { get; set; }
...
public int Author { get; set; } // changed type to int
}
更改查看到
<div class="editor-label">
@Html.LabelFor(model => model.Author)
</div>
<div class="editor-field">
@Html.DropDownList("AuthorId", String.Empty)
@Html.ValidationMessageFor(model => model.Author)
</div>
改变控制器到
private void PopulateAuthorDropDownList(object selectedPerson = null)
{
var personQuery = from d in db.People
orderby d.Name
select d;
ViewBag.AuthorId = new SelectList(personQuery, "Id", "UserName", selectedPerson); //Changed Author to AuthorId
}
和删除
modelBuilder.Entity<Post>()
.HasOptional(p => p.Author);
从 DataBaseContext
总之谢谢你的答案...:)
Anyway Thanks for the answers... :)
这篇关于ASP.NET MVC页面验证失败(该值是无效的。)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!