I have these 3 classes:
public class Product
{
public int ProductId { get; set; }
public int ClassId { get; set; }
public string Name { get; set; }
public virtual Class Class { get; set; }
}
public class Partner
{
public int PartnerId { get; set; }
public int ClassId { get; set; }
public string Name { get; set; }
public virtual Class Class { get; set; }
}
public class Price
{
public int PriceId { get; set; }
public int ClassId { get; set; }
public int ProductId { get; set; }
public int PartnerId { get; set; }
public float Cost { get; set; }
}
and I have 3 lists of data:
List<Product> products; List<Partner> partners; List<Price> prices;
How can I show partners in top row, products in left column and price (if it is available for each partner and product) in cells of table in MVC View?
As always I would start by designing a view model that will reflect the requirements of the view:
public class MyViewModel
{
public IEnumerable<Product> Products { get; set; }
public IEnumerable<PartnerPricesViewModel> PartnerProductPrices { get; set; }
}
public class PartnerPricesViewModel
{
public string PartnerName { get; set; }
public IEnumerable<Price> Prices { get; set; }
}
and then I will populate this view model in the controller action from our domain models and pass it to the view:
public ActionResult Index()
{
List<Product> products = ...
List<Partner> partners = ...
List<Price> prices = ...
var model = new MyViewModel
{
Products = products,
PartnerProductPrices =
from partner in partners
select new PartnerPricesViewModel
{
PartnerName = partner.Name,
Prices =
from product in products
select prices.FirstOrDefault(price =>
price.PartnerId == partner.PartnerId &&
price.ProductId == product.ProductId
)
}
};
return View(model);
}
and finally I will have a corresponding strongly typed view to the view model:
@model MyViewModel
<table>
<thead>
<tr>
<th></th>
@foreach (var product in Model.Products)
{
<th>@product.Name</th>
}
</tr>
</thead>
<tbody>
@foreach (var partner in Model.PartnerProductPrices)
{
<tr>
<td>@partner.PartnerName</td>
@foreach (var price in partner.Prices)
{
<td>
@if (price != null)
{
@price.Cost.ToString("c")
}
else
{
// There was no price found matching this
// product and partner => we display an empty cell
@:
}
</td>
}
</tr>
}
</tbody>
</table>
Your prices
list is very SQL friendly, but doesn't really fit the actual problem. I think your prices should be stored in a Dictionary<Tuple<Product, Partner>, Price>
instead of a List<Price>
.
Since this is MVC, I would use that dictionary as part of the view-model (along with the products and partners). Then displaying it as a table is going to be very straightforward.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.