How to display matrix table in asp.net mvc3?

I am participating in a small project that involves using entity structures and asp.net mvc3 to display many, many relationship databases in a matrix representation. Three tables include SalesPerson (Row label), Product (column label), and Sales:

Matrix table

How can I create / create this view in asp.net mvc3?

<table>
<tr>
    <th></th>
    @foreach (var m in Model)
    {
        foreach (var p in m.Products)
        {
            <th>@p.ProductName</th> 
        }           
    }
</tr>

    @foreach (var m in Model)
    {               
        foreach (var s in m.SalesPersons)
        {
          <tr>
               <td>@s.PersonName</td>

          </tr> 
         }
     }  
 @*Sales: a.Amount*@    
</table>
+5
source share
1 answer

Transform your data using a LINQ query like this

var salesTable =
    from s in m.Sales
    group s by s.SalesPerson.Label into g
    select new
    {
        rowKey = g.Key,
        rowData = g.Select(s => new { Product = s.Product, Amount = s.Amount }).OrderBy(s => s.Product.Label)
    };

Creating table rows is easy

@foreach (var tableRow in salesTable)
{
    <tr>
        <td>@tableRow.rowKey</td>
        @foreach (var sale in tableRow.rowData)
        {
            <td>@sale.Amount</td>
        }
    </tr>
}
+4
source

All Articles