I have 2 ViewModel
public class PostViewModel
{
[Key]
public int PostID { get; set; }
public int UserID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Picture { get; set; }
public DateTime CreateDate { get; set; }
public string Username { get; set; }
public string Fullname { get; set; }
public string CategoryID { get; set; }
public int LikeNumber { get; set; }
}
public class CommentViewModel
{
[Key]
public int CommentID { get; set; }
public int UserID { get; set; }
public string Username { get; set; }
public int PostID { get; set; }
public string Content { get; set; }
}
And I created an another ViewModel
public class BigViewModel
{
public List<CommentViewModel> CommentViewModels { get; set; }
public List<PostViewModel> PostViewModels { get; set; }
}
I want to use them on 1 View
@model ShareImage.Models.BigViewModel
@foreach (var item in Model.PostViewModels.OrderByDescending(x=>x.CreateDate))
{
<div class="row">
<div class="col-lg-12">
<div class="panel panel-info">
<div class="panel-heading">
<h3><b>TÀI KHOẢN:</b> @item.Username</h3>
<h3><b>NGÀY ĐĂNG:</b> @item.CreateDate</h3>
</div>
<div class="panel-body">
<div class="text-center">
<img src="@Url.Content(item.Picture)" class="rounded mx-auto d-block" alt="@item.Description" style="width:900px;height:600px" />
</div>
<hr />
<div class="panel-footer">
<h2>TIÊU ĐỀ: @item.Title</h2>
<h2>Mô tả: @item.Description</h2>
</div>
</div>
@Html.TextBox("Bình luận...") <button class="btn btn-success">Comment</button>
</div>
@foreach (var item1 in Model.CommentViewModels)
{
<div>@item1.Username</div>
<div>@item1.Content</div>
}
</div>
</div>
}
But when I run it has an error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[ShareImage.Models.PostViewModel]', but this dictionary requires a model item of type 'ShareImage.Models.BigViewModel'.
This is my controller:
public ActionResult Index()
{
var db = new ShareImageDbContext();
List<PostViewModel> model =new List<PostViewModel>();
var q = (from a in db.Posts
join b in db.Users on a.UserID equals b.UserID
select new
{
postID=a.PostID,
title=a.Title,
description=a.Description,
createDate=a.CreateDate,
picture=a.Picture,
username=b.Username,
}).ToList();
foreach (var item in q)
{
model.Add(new PostViewModel()
{
PostID = item.postID,
Title=item.title,
Description=item.description,
Picture=item.picture,
CreateDate=item.createDate,
Username=item.username,
});
}
return View(model);
}
I have not completed the code for CommentViewModel in Controller. But i think it's not important, because I'm going to complete it later.
I have tried many ways to solve it but it's still can't work. Please help me, thanks!