Issue
Im doing comment section for product and have some troubles with displaying comments view. I made model from 2 models to display them in one view, but my way to display IEnumerable as list gets me an error. How can i modify my code to get this working?
Model
public class DetailsViewModel
{
public Product Product { get; set; }
public IEnumerable<Comments> Comments { get; set; }
}
Controller
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);
}
View
@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>
i want to get something like this:
Solution
You can use a foreach loop to achieve your functionality. A foreach loop will iterate over your IEnumerable and display each element in the list. Specifically to your case, you can do:
<ul>
@foreach(var comment in Model.Comments)
{
<li>@comment.DateComment</li>
<li>@comment.Comment</li>
}
</ul>
Answered By - Rahul Sharma
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.