2009-07-13 6 views
1

私が取り組んでいる問題は、StackOverflowが質問、そのコメント、投稿に関連する投稿とコメントを表示する方法に非常に似ています。階層は同じです。MVCビューとパーシャルビューを使用してネストされたデータを表示する方法

これはASP.Net MVCでどのように達成できますか?

これまでのところ、私はこれがあります(私は私の質問を読みやすくするためにSOサイトに類似したファイルを命名した)

ビュー/質問/ Details.aspx

public class QuestionsController : Controller 
{ 
    public ActionResult Details(int? questionId) 
    { 
     Question question= _db.Question .First(i => i.QuestionId== questionId); 
     return View(question); 
    } 
} 

これは、詳細をロードします質問を表示します。

QuestionCommentというユーザーコントロールがありますが、質問のコメントが表示されるはずですが、配線方法についてはわかりません。私はDinnersソリューションをガイドとして使用しています。

+0

これは – Picflight

答えて

4

コメント付き質問を表示するViewModelを作成します。このような何か:

public class QuestionViewModel 
{ 
    public Question Question { get; set; } 
    public IEnumerable<Comment> Comments { get; set; } 
} 

あなたのコントローラになる:

public class QuestionsController : Controller 
{ 
    public ActionResult Details(int? questionId) 
    { 
     var question = _db.Question.First(x => x.QuestionId == questionId); 
     var comments = _db.Comment.Where(x => x.QuestionId == questionId).ToList(); 
     var model = new QuestionViewModel { 
      Question = question, 
      Comments = comments 
     }; 
     return View("Details", model); 
    } 
} 

あなたの "詳細" 表示:

<%@ Page Inherits="System.Web.Mvc.ViewPage<QuestionViewModel>" %> 

<% Html.Renderpartial("QuestionControl", model.Question); %> 
<% Html.Renderpartial("CommentsControl", model.Comments); %> 

"QuestionControl" 部分ビュー:

<%@ Control Inherits="System.Web.Mvc.ViewUserControl<Question>" %> 

<h3><%= Model.Title %></h3> 

... 

「CommentsControl "部分表示:

<%@ Control Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Comment>>" %> 

<ul> 
<% foreach (var comment in Model) { %> 
    <li> 
     <%= comment.Content %> 
    </li> 
<% } %> 
</ul> 

... 
+0

+1これは、物事をすることの見解を再現するように、パターンIMHO –

0

あなたの意見では、このようなものを書いてください。

<% foreach (var question in Model.Questions) { %> 

<%=question.bodyText%> 

<%}%> 

希望があれば、コメントを投稿しないと私はあまり秘密にしません。

+0

あるいは、 <%Html.Renderpartial( "commentsControl"、質問)に保存されます。 %> – griegs

+0

これは私が別々のUserControlで自分のコメントを持つ必要はないことを意味しますか? – Picflight

+0

質問のIDをどのように渡して、その質問に関連するコメントしか得られないでしょうか? – Picflight

関連する問題