2012-03-08 4 views
9

그래서 내 데이터베이스의 모든 스레드를 배치하는 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; } 
} 
+0

당신은'Thread' 객체가 어떻게 보이는지 보여줄 필요가 있습니다. – RPM1984

+0

그래서 modelstate 검사를 제거하고 그것이 효과가 있는지 확인하려고했습니다. 이제이 오류가 발생합니다 : "엔터티 개체를 IEntityChangeTracker의 여러 인스턴스에서 참조 할 수 없습니다." –

+0

이제 Entity Framework에 대해 이야기합니다. 더 많은 정보를 제공해야합니다. '_repository.AddComment (thread, comment)'는 무엇을합니까? 기존의 스레드를 ThreadId로 가져 와서'thread.Comments.Add (newComment);를 실행 한 다음 스레드를 저장하기 만하면됩니다. 그것이어야합니다. – RPM1984

답변

23

사용하여 코드가 오류를 반복하는 그리고 여기의 요청에 따라 스레드의 내부 전부입니다. 그런 다음 어떤 필드와 어떤 개체가 유효성 검사에서 실패했는지 확인할 수 있습니다. 그리고 거기에서 갈 수 있습니다. IsValid 속성을 살펴보면 충분한 정보를 얻지 못할 것입니다.

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

그런 다음 오류를 반복합니다.

0

오류를 확인하기 전에 모델 상태가 유효하지 않은 이유를 알아야합니다. 오류 목록을보고 디버깅하여 쉽게 수행 할 수 있습니다.

두 번째 오류는 stackoverflow 지침으로 작성된 것으로 생각되는 별도의 질문이어야합니다.

관련 문제