【问题标题】:ASP.NET - place data in table based on table columnASP.NET - 根据表列将数据放入表中
【发布时间】:2014-12-31 01:27:24
【问题描述】:

在 ASP.NET 中,我正在动态创建一个表,包括列和行。

<table>
<thead>
    <tr>
        <th scope="col">To location</th>
        @foreach (String itemName in ViewBag.itemNames)
        {
            <th scope="col">@itemName</th>
        }
    </tr>

</thead>
<tbody>
    @foreach (var transaction in Model)
    {
        <tr>
            <td>@transaction.toLocation</td>

            @foreach (var item in transaction.itemList)
            {
                <td>@item.quantity</td>
            }
        </tr>
    }
</tbody>
</table>

在 thead 元素中,我得到一列,其中包含项目发送到的位置,以及可能在事务中的每个项目的列。 tbody 元素中使用的 itemList 与 thead 中的 itemName 列的名称相同,加上项目的数量。我正在寻找的第二个 foreach 循环是这样的:

foreach(item in transaction.itemList)
{
    @thead.findColumn(@item.itemName) // find the column name that's the same as the itemName
    <td>@item.quantity</td> // place the data in that column
}

有人知道怎么做吗?

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    您可以遍历每一行的所有列名并使用 LINQ 来获取您正在寻找的项目:

    <tbody>
        @foreach (var transaction in Model)
        {
            <tr>
                <td>@transaction.toLocation</td>
    
                foreach(String itemName in ViewBag.itemNames)
                {
                    <td>transaction.itemList.Where(x => x.itemName == itemName).Select(x => x.quantity).FirstOrDefault()</td>
                }
    
            </tr>
        }
    </tbody>
    

    您可能需要在文件顶部包含此内容:

    @using System.Data.Linq
    

    【讨论】:

    • 迟到的反应,抱歉。效果很好,非常感谢!
    猜你喜欢
    • 2019-02-17
    • 2014-01-23
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 2015-02-12
    • 2021-09-23
    • 2015-08-11
    相关资源
    最近更新 更多