2012-03-08 132 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 2012-03-08 03:34:39

+0

所以我試圖刪除modelstate檢查,看看是否工作。現在我得到這個錯誤:「一個實體對象不能被多個IEntityChangeTracker實例引用。」 – 2012-03-08 04:11:27

+0

現在你在談論實體框架。您需要提供更多信息。 '_repository.AddComment(thread,comment)'做了什麼?好像你需要做的就是通過它的ThreadId獲取現有線程,然後執行'thread.Comments.Add(newComment);'然後保存線程。應該是這樣。 – RPM1984 2012-03-08 04:28:26

回答

23

使用下面的代碼在錯誤進行迭代。然後你可以看到哪些字段和哪個對象在驗證上失敗。然後你可以從那裏去。只要查看IsValid屬性就不會提供足夠的信息。

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

然後遍歷錯誤。

0

在檢查錯誤之前,您需要知道爲什麼模型狀態無效。您可以通過調試和查看錯誤列表來輕鬆完成此操作。

第二個錯誤應該是一個單獨的問題,因爲我相信這是寫在stackoverflow指南。