Zarobiek Zarobiek - 1 month ago 12
ASP.NET (C#) Question

Wall full of post and comment in .NET

I have a problem with my small website service. I have to code some Wall with the post and comment from user.
I have some model for 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; }
}


and for Comment:

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; }
}


I'm using identity model as u can see. My problem is:

1) How i can display all Post + Comment for any Post in the view?

2) Maybe partial view for comment? But how?

3) I have view:

@foreach (var item1 in Model)
{
<p>
<span style="font-weight: bolder">
@Html.DisplayFor(modelItem => item1.ApplicationUser.UserName)
Date: @Html.DisplayFor(modelItem => item1.PostDateTime)
</span>
<br/>
@Html.DisplayFor(modelItem => item1.PostContent)
</p>
}


But that view display only all post without comment.
Please help!

Answer

When I need to mix up things coming from different models, I use a ViewModel usually.

It's a model made for specific views where I put data from various sources or particular computations.

Basically it's just another model, with the fields needed.

In your case it could be something like

  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; }
}

And in your action you will pass both a Post and a Comment model, assing to PostAndComment the various fields from both and pass that to the View.

The action should be something like

ActionResult PostComment(Post post, Comment comment)
{
    PostAndComments postcomment = new PostAndComments
        {
            IDPost = post.ID,
            IDComment = comment.ID,
            etc... etc...
        }
}

Making it throught a partial view would add unnecessary complexity.