그래서 내 데이터베이스의 모든 스레드를 배치하는 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"/>
}
스레드 인 모델이다.
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; }
}
당신은'Thread' 객체가 어떻게 보이는지 보여줄 필요가 있습니다. – RPM1984
그래서 modelstate 검사를 제거하고 그것이 효과가 있는지 확인하려고했습니다. 이제이 오류가 발생합니다 : "엔터티 개체를 IEntityChangeTracker의 여러 인스턴스에서 참조 할 수 없습니다." –
이제 Entity Framework에 대해 이야기합니다. 더 많은 정보를 제공해야합니다. '_repository.AddComment (thread, comment)'는 무엇을합니까? 기존의 스레드를 ThreadId로 가져 와서'thread.Comments.Add (newComment);를 실행 한 다음 스레드를 저장하기 만하면됩니다. 그것이어야합니다. – RPM1984