模型状态无效
本文关键字:无效 状态 模型 | 更新日期: 2023-09-27 18:27:02
所以我有一个名为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))
{
<input type="text" name="AddComment" id="text" />
<input type="submit" value="Save"/>
}
在上面代码的例子中,mod是一个线程模型。按照要求,这里是线程内部的一切:
public Thread()
{
this.ChildComments = new HashSet<Comment>();
}
public int Id { get; set; }
public string TopicHeader { get; set; }
public string TopicBody { get; set; }
public Nullable<int> UpVotes { get; set; }
public Nullable<int> DownVotes { get; set; }
public int ProfileId { get; set; }
public int TagId { get; set; }
public virtual Profile Profile { get; set; }
public virtual ICollection<Comment> 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; }
}
使用下面的代码遍历错误。然后,您可以看到哪个字段和哪个对象在验证中失败。然后你就可以从那里走了。仅仅查看IsValid属性并不能提供足够的信息。
var errors = ModelState.Values.SelectMany(v => v.Errors);
然后遍历错误。
在检查错误之前,您需要了解模型状态无效的原因。通过调试并查看错误列表,您可以很容易地做到这一点。
第二个错误应该是一个单独的问题,因为我相信它会写在stackoverflow指南中。