在视图中显示外键一次?

时间:2016-10-19 12:55:39

标签: asp.net-mvc asp.net-mvc-4 razor

我有两个模型,帖子和评论。后PK是评论中的外键(一对多)。然后我有一个带帖子和评论的ViewModel。

这是我的控制器

public ActionResult Index()
{
    var model = db.Comments.Include(p => p.Post)
        .OrderByDescending(p => p.CommentId).ToList()
        .Select(p => new ListCommentsViewModel
        {
            Comment = p.PostComment,
            Message = p.Post.Message
        }).ToList();

    return View(model);
}

我稍后会过滤外键值,因此,外键的值将始终相同。如何在View中显示一次。这是有效的

@model IEnumerable<FreePost.Viewmodels.ListCommentsViewModel>
@foreach (var item in Model)
            {
                @Html.DisplayFor(modelItem => item.Message)
                @Html.DisplayFor(modelItem => item.Comment)
            }

但是我想在foreach意义上使用@Html.DisplayFor(modelItem => item.Message)外键消息的值总是相同的。

更新

这是我的模特帖子和评论

 public class Post
    {
        public Post()
        {
            Vote = new HashSet<Vote>();
            Comment = new HashSet<Comment>();
        }

        public int PostId { get; set; }
        public string Message { get; set; }
        public DateTime MessageDate { get; set; }

        public virtual ApplicationUser User { get; set; }
        public virtual ICollection<Vote> Vote { get; set; }

        public ICollection<Comment> Comment { get; set; }
    }

    public class Comment
    {
        public Comment() { }

        public int CommentId { get; set; }
        public string PostComment { get; set; }
        public DateTime CommentDate { get; set; }

        public int PostRefId { get; set; }

        [ForeignKey("PostRefId")]
        public virtual Post Post { get; set; }
    }

更新2

使用我的代码,我在视图中得到了这个结果

post 1
Comment 1
post 1
Comment 2
post 1
Comment 3

我想得到这个结果(感觉帖子是相同的FK)

post 1
Comment 1
Comment 2
Comment 3

1 个答案:

答案 0 :(得分:0)

在linq查询

中尝试加入
var model = (from p in db.Post
            join c in db.Comments on p.PostId equals c.PostId
            select new { p.Post, c.PostComment})
            .OrderByDescending(p => p.CommentId);

查看页面

@model IEnumerable<FreePost.Viewmodels.ListCommentsViewModel>
string post="";
@foreach (var item in Model)
{
   if(post!=item.Post)
   {
   @Html.DisplayFor(modelItem => item.Post)
   }
   @Html.DisplayFor(modelItem => item.PostComment)
   post=item.Post;
}

 var model = (from p in db.Post
            join c in db.Comments on p.PostId equals c.PostId into g
            select new { p.Post, 
            comments = g.Select(x =>x.PostComment)}).AsEnumerable()
            .Select(x => new {x.Post,comments = String.Join(",",x.PostComment)})
            .OrderByDescending(p => p.CommentId);

查看页面

 @model IEnumerable<FreePost.Viewmodels.ListCommentsViewModel>

    @foreach (var item in Model)
    {
       @Html.DisplayFor(modelItem => item.Post)
       @Html.DisplayFor(modelItem => item.comments ) //All comments display in single line with splited by ",".If you want different line using split function to split the string

    }