2017-04-03 48 views
0

我有一个从BlogResponseModel填充的博客,并且每个Blog条目的相关注释都保存在列表中。它看起来像这样:C#MVC - 在模型列表中访问项目

public class BlogResponseModel 
{ 
    public int Id { get; set; } 
    public DateTime SubmissionDate { get; set; } 
    public string Title { get; set; } 
    public string ImageID { get; set; } 
    public string ImageAttribution { get; set; } 
    public string Body { get; set; } 
    public List<BlogCommentModel> CommentList { get; set; } 
} 

评论被收集并且每个评论都与上面的Id元素相关。该BlogCommentModel看起来是这样的:

public class BlogCommentModel 
{ 
    public int CommentId { get; set; } 
    public int CommentCount { get; set; } 
    public DateTime CommentDate { get; set; } 
    public string Commenter { get; set; } 
    public string CommenterEmail { get; set; } 
    public string Comment { get; set; } 
    public int BlogParentId { get; set; } 
} 

在我看来,我使用一个foreach格式化并显示每个博客条目,这是工作得很好。我碰到墙壁的地方是想知道如何在每篇博客文章的底部嵌入相关评论。

这是当前在视图中的尝试,让我难住。我做一个foreach渲染博客文章...

@foreach (var response in Model) 
    { 
     // enter all the Blog specifics here... 

在这一点上,博客条目被渲染,我们准备添加评论:

<div class="message row"> 
    <div> 
     <H5>Comments</H5> 
    </div> 
    @foreach (var comment in ?? WHAT ?? (how do I access BlogResponseModel) 
    { 
     <div class="replies span12"> 
      <div class="reply"> 
       <div class="created pull-right"> 
        @comment.CommentDate 
       </div> 
       <div class="created"> 
        @comment.Commenter 
       </div> 
       <div> 
        @comment.Comment 
       </div> 
      </div> 
     </div> 
    } 
</div> 

如何填充来自BlogResponseModel中的List CommentList的评论?

在此先感谢您的建议。我是MVC的新手,仍然围绕着架构进行思考。

+0

您的看法是@model IEnumerable 吗? –

+1

通过查看你的'@foreach(模型中的无功响应)'。我想你可以在你的第二个foreach中使用'response.CommentList'。 –

+0

是否要在博客foreach循环中显示注释,或者是否希望在循环外显示注释? –

回答

0

您可以查看

@foreach (var item in Model) 
{ 
    @Html.DisplayFor(modelItem => item.Title) 

    @foreach (var myBlogCommentModel in @item.BlogCommentModel) 
    { 
     @myBlogCommentModel.Commenter 
     @myBlogCommentModel.CommenterEmail 
    } 
} 

public virtual ICollection<BlogCommentModel> CommentList { get; set; } 

代替

public List<BlogCommentModel> CommentList { get; set; } 

然后,我希望这将有助于。

+0

甜!一个更新,以防其他人有这个相同的问题。修改(在)foreach(var myBlogCommentModel in(at)item.BlogCommentModel)读取(at)foreach(var item.CommentList中的myBlogCommentModel),它的作品非常漂亮! ! – DJGray