gpt4 book ai didi

ASP.NET MVC 页面验证失败(值无效。)

转载 作者:行者123 更新时间:2023-12-04 18:19:13 26 4
gpt4 key购买 nike

我正在尝试使用具有一对多关系的 Entity Framework 创建 ASP.NET MVC 应用程序。为此,我已成功地将适当的项目列表加载到下拉控件(在创建 View 中),但是当我单击创建按钮(在创建 View 中)页面验证失败时,验证错误消息为 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);
}

Controller
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 是一个有效值。我在这里想念什么?

提前致谢...

最佳答案

你没有展示 Author对象看起来像,

假设如果是这样,

public class Author
{
public int Id{get;set;}
public string Name{get;set;}
}

尝试这个,
<div class="editor-label">
@Html.LabelFor(model => model.Author)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Author.Id, ViewBag.Author, "Select an Author")
@Html.ValidationMessageFor(model => model.Author)
</div>

关于ASP.NET MVC 页面验证失败(值无效。),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11030459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com