I am fairly new to MVC and trying to explore more into ViewModels. I have an product category page that I would like to display product categories as well as products and their associated images. I am going to simplify some of these tables and just focus on the logic of returning this data to the view. I have the view working with the populated dropdownlist, but I am not sure how to populate the ProductViewModel within the CategoryViewModel.
Database
Category Table
CategoryId
CategoryName
CategoryDescription
Product Table
ProductId
ProductName
ProductDescription
ProductPrice
CategoryId
ProductImage Table
ProductId
ProductImage1
ProductImage2
ProductImage3
ProductImage4
ProductImage5
ProductImage6
ProductImage7
ProductImage8
ProductImage9
ProductImage10
ViewModel
public class ProductViewModel
{
public Product ProductVM { get; set; }
public ProductImage ProductImageVM { get; set; }
}
public class CategoryViewModel
{
public List<Category> Category { get; set; }
public List<ProductViewModel> Products { set;get;}
}
Controller
public ActionResult Index()
{
var model = new CategoryViewModel();
model.Category = db.Categories.OrderBy(d => d.CategoryName).ToList();
model.Products = from p in db.Products
join pi in db.ProductImages on p.ProductId equals pi.ProductId
orderby p.ProductPrice descending
return View(model);
}
View
@model CategoryViewModel
@Html.DropDownListFor(x => x.CategoryId, new SelectList(Model.Category, "CategoryId", "CategoryName"), "View all Categories")
<table>
@foreach (var product in Model.Products)
{
<tr>
<td>@item.ProductImage.ProductImage1</td>
<td>@item.Product.ProductName</td>
<td>@item.Product.ProductPrice</td>
<td>@item.Product.ProductDescription</td>
</tr>
}
</table