2012-03-08 83 views
1

私はスレッドとコメントで取りたいビューを持っているので、投稿を行うときに両方を持ち、両方を更新できるようにします。私は1つだけのアクションの結果であり、他はそれがsucceded場合は、メインページに戻りますポストされながらビューを返す2つの方法があります複数の値をビューに渡す

@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> 

:ここ

は図です。 ここでの方法は以下のとおりです。

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

あなたはその後、内コメントとスレッドの両方にアクセスできるビューにその単一のビューモデルを渡した後、コメントやスレッドを保持するためのViewModelクラスを作成することができます= myThread

1

ViewBag.Threadを使用することができますそれ。

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 

個々のコメントとスレッドオブジェクトに到達するには、さらに深くする必要があります。

関連する問題