Skip to content

Instantly share code, notes, and snippets.

@stevebrownlee
Last active August 17, 2018 04:22
Show Gist options
  • Save stevebrownlee/4da968bb20c9e2b3d1ed3cdc5b7b6d2e to your computer and use it in GitHub Desktop.
Save stevebrownlee/4da968bb20c9e2b3d1ed3cdc5b7b6d2e to your computer and use it in GitHub Desktop.
C# Bangazon product types view with products
using System.Collections.Generic;
namespace Bangazon.Models
{
public class GroupedProducts
{
public int TypeId { get; set; }
public string TypeName { get; set; }
public int ProductCount { get; set; }
public IEnumerable<Product> Products { get; set; }
}
}
@model Bangazon.Models.ProductViewModels.ProductTypesViewModel
@{
ViewData["Title"] = "Product Types";
}
<h2 class="top-buffer">Product Types</h2>
@foreach (var type in Model.GroupedProducts)
{
<div class="row">
<div class="col-md-12">
<a asp-controller="ProductTypes" asp-action="Detail" asp-route-type="@type.TypeId">
<h4>@type.TypeName (@Html.DisplayFor(modelItem => type.ProductCount))</h4>
</a>
</div>
</div>
foreach (var product in type.Products)
{
<div class="row">
<div class="col-md-10">
@product.Title
</div>
<div class="col-md-2">
@product.Price.ToString("C")
</div>
</div>
}
}
public async Task<IActionResult> Index()
{
var model = new ProductTypesViewModel();
// Get line items grouped by product id, including count
var counter = from product in _context.Product
group product by product.ProductTypeId into grouped
select new { grouped.Key, myCount = grouped.Count() };
// Build list of Product instances for display in view
model.GroupedProducts = await (
from t in _context.ProductType
join p in _context.Product
on t.ProductTypeId equals p.ProductTypeId
group new { t, p } by new { t.ProductTypeId, t.Label } into grouped
select new GroupedProducts
{
TypeId = grouped.Key.ProductTypeId,
TypeName = grouped.Key.Label,
ProductCount = grouped.Select(x => x.p.ProductId).Count(),
Products = grouped.Select(x => x.p).Take(3)
}).ToListAsync();
return View(model);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment