I want to display a list product's name group by categoryId, this is my code:
I want to my view display result:
Desktop
|_ PC HP - Red
|_ PC Dell - Yellow
|_ PC Asus - Red
SmartPhone
|_ Lumia 720 - Blue
My GroupModel:
public class GroupModel
{
public Category Categories { get; set; }
public Product Products { get; set; }
}
My controller:
List<Category> listCategories = new List<Category>
{
new Category {Id = 1, CateName = "SmartPhone"},
new Category {Id = 2, CateName = "Laptop"},
new Category {Id = 3, CateName = "Desktop"},
};
List<Product> listProducts = new List<Product>
{
new Product {Id = 1, ProdName = "Lumia 720", CategoryId = 1, ColorId = 2},
new Product {Id = 2, ProdName = "PC HP", CategoryId = 3, ColorId = 1},
new Product {Id = 3, ProdName = "PC Dell", CategoryId = 3, ColorId = 1},
new Product {Id = 4, ProdName = "Laptop Lenovo", CategoryId = 2, ColorId = 2},
new Product {Id = 5, ProdName = "Lumia 920", CategoryId = 1, ColorId = 2},
new Product {Id = 6, ProdName = "Laptop Dell", CategoryId = 2, ColorId = 3},
new Product {Id = 7, ProdName = "Laptop HP", CategoryId = 2, ColorId = 3}
};
List<Color> listColor = new List<Color>
{
new Color {ColorId = 1, ColorName = "Blue"},
new Color {ColorId = 2, ColorName = "Yellow"},
new Color {ColorId = 3, ColorName = "Red"}
};
var query = from c in listCategories
join p in listProducts on c.Id equals p.CategoryId
select new GroupModel
{
Categories = c,
Products = p
};
return View(query.ToList());
and this is my view to bind a list. I'm using GroupModel to nested ProductModel and CategoryModel
@model IEnumerable<Test.Models.GroupModel>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(model => item.Categories.CateName)
</td>
</tr>
<tr>
<td>
@Html.Label("|__ ") @Html.DisplayFor(model => item.Products.ProdName)
</td>
</tr>
}