模型状态无效

所以我有一个名为index的视图,它列出了我数据库中的所有线程。 然后在该视图中我加载了线程上的所有注释。 当我打电话给我应该创建新评论的表单时,它一直告诉我模型状态无效。 它告诉我它无法从类型字符串转换为类型配置文件或注释或标记。 最初我把它作为我的代码:

public ActionResult AddComment(Thread thread, string commentBody) { if (ModelState.IsValid) { _repository.AddComment(thread, comment); TempData["Message"] = "Your comment was added."; return RedirectToAction("Index"); } 

然后我改成了这个:

  public ActionResult AddComment(Thread thread, string commentBody) { Profile profile = _profileRepository.Profiles.FirstOrDefault(x => x.Id == thread.ProfileId); Tag tag = _tagRepository.Tags.FirstOrDefault(t => t.Id == thread.TagId); thread.ThreadTag = tag; thread.Profile = profile; Comment comment = new Comment() { CommentBody = commentBody, ParentThread = thread }; if (ModelState.IsValid) { _repository.AddComment(thread, comment); TempData["Message"] = "Your comment was added."; return RedirectToAction("Index"); } 

这仍然告诉我模型状态无效。 如何获得它以便它不会尝试改变状态?

此处还有用于调用此操作的表单:

 @using(Html.BeginForm("AddComment", "Thread", mod)) {   } 

在上面的代码实例中,mod是一个线程的模型。 这里要求的是线程内的所有内容:

  public Thread() { this.ChildComments = new HashSet(); } public int Id { get; set; } public string TopicHeader { get; set; } public string TopicBody { get; set; } public Nullable UpVotes { get; set; } public Nullable DownVotes { get; set; } public int ProfileId { get; set; } public int TagId { get; set; } public virtual Profile Profile { get; set; } public virtual ICollection ChildComments { get; set; } public virtual Tag ThreadTag { get; set; } 

最后评论类:

  public partial class Comment { public int Id { get; set; } public string CommentBody { get; set; } public int UpVotes { get; set; } public int DownVotes { get; set; } public virtual Thread ParentThread { get; set; } } 

使用下面的代码迭代错误。 然后,您可以查看哪些字段以及哪些对象在validation时失败。 然后你可以从那里去。 只是查看IsValid属性不会提供足够的信息。

 var errors = ModelState.Values.SelectMany(v => v.Errors); 

然后循环错误。

在检查错误之前,您需要知道为什么模型状态无效。 您可以通过调试和查看错误列表轻松完成此操作。

第二个错误应该是一个单独的问题,因为我认为是在stackoverflow指南中编写的。