墙上满是.net的帖子和评论
本文关键字:评论 net | 更新日期: 2023-09-27 18:12:11
我的小网站服务有问题。我必须编码一些墙的帖子和评论从用户。我有一些Post模型:
public class Post
{
public int ID { get; set; }
public string PostContent { get; set; }
public DateTime PostDateTime { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
和注释:
public class Comment
{
public int ID { get; set; }
public string CommentContent { get; set; }
public DateTime CommentDateTime { get; set; }
public int PostId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual Post Post { get; set; }
}
如何在视图中显示所有帖子和他的评论?
当我需要混合来自不同模型的东西时,我通常使用ViewModel。
这是一个为特定视图创建的模型,我在其中放入了来自不同来源或特定计算的数据。
基本上它只是另一个模型,带有所需的字段。
在你的例子中可以是
public class PostAndComments
{
public int IDPost { get; set; }
public int IDComment { get; set; }
public string CommentContent { get; set; }
public DateTime CommentDateTime { get; set; }
public string PostContent { get; set; }
public DateTime PostDateTime { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual Post Post { get; set; }
}
在您的操作中,您将传递Post和Comment模型,将来自两者的各种字段传递给PostAndComment,并将其传递给View。
动作应该类似于
ActionResult PostComment(Post post, Comment comment)
{
PostAndComments postcomment = new PostAndComments
{
IDPost = post.ID,
IDComment = comment.ID,
etc... etc...
}
}
通过局部视图将增加不必要的复杂性。