2012-03-08 84 views
1

我有一個觀點,我想在線程和註釋中這樣做,當我執行該帖子時,它將具有並且能夠更新兩者。將多個值傳遞到視圖中

這裏是視圖:

@model GameDiscussionBazzar.Data.Comment 
@{ 
    ViewBag.Title = "EditComment"; 
    Layout = "~/Views/Shared/_EditCommentLayout.cshtml"; 
} 
<div class="EditComment"> 
<h1> 
    Edit Comment 
</h1> 
@using (Html.BeginForm("EditThreadComment", "Comment")) 
{ 
    <div class="EditingComment"> 
     @Html.EditorForModel() 
     @Html.Hidden("comment", Model) 
     @Html.HiddenFor(i => i.ParentThread) 
     <input type="submit" value="Save"/> 
     @Html.ActionLink("Return without saving", "Index") 

    </div> 
} 
</div> 

我有2種方法之一就是動作結果的同時,另一種是返回到主頁,如果它succeded後返回視圖。 這裏的方法:

public ActionResult EditThreadComment(int commentId) 
    { 
     Comment comment = _repository.Comments.FirstOrDefault(c => c.Id == commentId); 

     return View(comment); 
    } 
    [HttpPost] 
    public ActionResult EditThreadComment(Comment comment, Thread thread) 
    { 
     var c = thread.ChildComments.FirstOrDefault(x => x.Id == comment.Id); 
     thread.ChildComments.Remove(c); 
     if (ModelState.IsValid) 
     { 
      _repository.SaveComment(comment); 
      thread.ChildComments.Add(comment); 
      _tRepo.SaveThread(thread); 
      TempData["Message"] = "Your comment has been saved"; 
      return RedirectToAction("Index", "Thread"); 
     } 
     else 
     { 
      TempData["Message"] = "Your comment has not been saved"; 
      return RedirectToAction("Index", "Thread"); 
     } 
    } 

如此反覆,我的問題是我如何通過2個參數到視圖?或者我如何傳遞線程的值?

回答

0

您可以使用ViewBag.Thread = MyThread的

1

您可以創建一個視圖模型類來保存評論和主題,然後傳遞單一視圖模型視圖,然後可以訪問兩個註釋,並在線程中它。

4

爲了傳回多個值,您應該創建一個ViewModel,它可以容納任何想要更改的對象和值,並且(最終)將其傳遞迴視圖。因此,創建一個像這樣的新模型...(我現在不在編譯器中,所以如果某些代碼不能生成,我很抱歉)。

public class PostViewModel 
{ 
    public Comment Comment { get; set; } 
    public Thread Thread { get; set; } 
} 

在你的控制器中,你需要基本上在你的PostViewModel之間來回轉換。

public ActionResult EditThreadComment(int commentId) 
{ 
    PostViewModel post = new PostViewModel(); 

    Comment comment = _repository.Comments.FirstOrDefault(c => c.Id == commentId); 
    post.Comment = comment; 
    post.Thread = new Thread(); 

    return View(post); 
} 

public ActionResult EditThreadComment(PostViewModel post) 
{ 
    Comment comment = post.Comment; 
    Thread thread = post.Thread; 

    // Now you can do what you need to do as normal with comments and threads 
    // per the code in your original post. 
} 

而且,在您看來,您現在已經強制類型爲PostViewModel。所以,在頂端...

@model GameDiscussionBazzar.Data.PostViewModel 

而且你將不得不進入更深層次的單個評論和線程對象。