所以我有一个名为index的视图,它列出了我数据库中的所有线程.然后在该视图中我加载了线程上的所有注释.当我打电话给我应该创建新评论的表单时,它会一直告诉我模型状态无效.它告诉我它无法从类型字符串转换为类型配置文件或注释或标记.最初我把它作为我的代码:
public ActionResult AddComment(Thread thread, string commentBody)
{
if (ModelState.IsValid)
{
_repository.AddComment(thread, comment);
TempData["Message"] = "Your comment was added.";
return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)
然后我改为:
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");
}
Run Code Online (Sandbox Code Playgroud)
这仍然告诉我模型状态无效.如何获得它以便它不会尝试改变状态?
此处还有用于调用此操作的表单:
@using(Html.BeginForm("AddComment", "Thread", mod))
{
<input type="text" name="AddComment" id="text" />
<input type="submit" value="Save"/>
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码实例中,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; }
Run Code Online (Sandbox Code Playgroud)
最后评论类:
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; }
}
Run Code Online (Sandbox Code Playgroud)
小智 38
使用下面的代码迭代错误.然后,您可以查看哪些字段以及哪些对象在验证时失败.然后你可以从那里去.只是查看IsValid属性不会提供足够的信息.
var errors = ModelState.Values.SelectMany(v => v.Errors);
Run Code Online (Sandbox Code Playgroud)
然后循环错误.
| 归档时间: |
|
| 查看次数: |
16570 次 |
| 最近记录: |