我正在为产品做评论部分,在显示评论视图时会遇到一些麻烦。我从2个模型制作模型以在一个视图中显示它们,但是将IEnumerable显示为列表的方式使我出错。如何修改我的代码以使其正常工作?
型号
public class DetailsViewModel
{
public Product Product { get; set; }
public IEnumerable<Comments> Comments { get; set; }
}
控制器
public ActionResult ProductDetails(int? id)
{
DetailsViewModel detailsViewModel = new DetailsViewModel();
detailsViewModel.Product = db.Product.Find(id);//this is working
detailsViewModel.Comments = db.Comments.Where(c => c.Id_Product == id).OrderBy(x => x.DateComment).ToList();
return View(detailsViewModel);
}
查看
@model Database.Models.DetailsViewModel
<ul>
@Html.DisplayFor(x => x.Comments.DateComment) //getting error here 'IEnumerable<Comments>'
@Html.DisplayFor(x => x.Comments.Comment) // does not containt definiton for 'Comment'
<ul>
我想得到这样的东西:
答案 0 :(得分:3)
您可以使用foreach
循环来实现您的功能。一个foreach循环将遍历您的IEnumerable
并显示列表中的每个元素。具体针对您的情况,您可以执行以下操作:
<ul>
@foreach(var comment in Model.Comments)
{
<li>@comment.DateComment</li>
<li>@comment.Comment</li>
}
<ul>
答案 1 :(得分:1)