我正在处理产品详细信息页面上的评论。我想显示该产品的所有评论。通常,我使用
ViewBag
来选择所有评论:
ViewBag.Comment = await _context.ProductComments
.Where(n => n.ProductId == sp.ProductItems.ProductId)
.ToListAsync();
然后在视图中:
IEnumerable<ProductComment> listComment = ViewBag.Comment as IEnumerable<ProductComment>;
@foreach (var comment in listComment)
{
<div>
<p>@comment.Detail</p>
<p>@comment.CreatedBy</p>
<p>@comment.CreateDate</p>
</div>
}
但是现在我注意到在
Product
模型类中,我有一个属性
public virtual ICollection<ProductComment> ProductComments { get; set; }
因为一件产品可以有很多评论。我尝试在视图中使用此属性并更改
foreach
,如下所示:
@foreach (var comment in Model.ProductItems.Product.ProductComments)
{
<div>
<p>@comment.Detail</p>
<p>@comment.CreatedBy</p>
<p>@comment.CreateDate</p>
</div>
}
但是评论区一片空白。我在聊天 GPT 和 YouTube 中搜索,但仍然不起作用。
有什么正确的方法还是我误解了什么?我真的很感激任何指导。感谢您的阅读
解决方案:您需要在控制器中包含 ProductComments
var product = await _context.ProductVariations
.Include(n => n.ProductItems.Product.ProductComments)
.Include(n => n.ProductItems.Product.Category)