【问题标题】:How can I display a matrix table in asp.net mvc3?如何在 asp.net mvc3 中显示矩阵表?
【发布时间】:2012-05-25 17:48:36
【问题描述】:

我正在进行一个小项目,涉及使用实体框架和 asp.net mvc3 在矩阵视图中显示多对多关系数据库。涉及的三个表分别是SalesPerson(行标签)、Product(列标签)和Sales:

如何在 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>

【问题讨论】:

  • 您可以只使用嵌套循环,或者更好的是,创建适合您的视图的 ViewModel

标签: c# html asp.net-mvc razor matrix


【解决方案1】:

使用与此类似的 LINQ 查询转换您的数据

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)
    };

生成表格行很容易

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多