【问题标题】:Make dynamically generate table stay in form when not enough item in row当行中没有足够的项目时,动态生成表格保持形式
【发布时间】:2015-08-04 00:17:31
【问题描述】:

我正在使用 asp.net MVC。我已经在我的视图中动态生成了一行包含 5 个项目的表格。但是当模型没有足够的 5 个项目时,我有一个问题,项目宽度会增加以填充如下所示的行:

| x | x | x | x | x | (when have >=5 item)

|    x    |    x    | (when have <5 item, in this case is 2)

| x | x |             (what I want to display) 

这是我的cshtml代码:

<table style="width:100%;height:100%">
    @{
        int count = 0;
        foreach (var thread in Model)
        {
            if (count % 5 == 0)
            {
                @:<tr>
            }
            <td style="width:20%">
                //thread details here
            </td>
            count++;
            if (count % 5 == 0)
            {
                @:</tr>
            }
        }
    }
</table>

我可以更改为每行 2 个项目或使用固定宽度 in ,但这不是我的目标。 你能建议我一些改进我的桌子的方法吗?

【问题讨论】:

  • td中删除style="width:20%"
  • 感谢您的回复,但我试过了,没有任何改变。我希望 2 个项目以 40% 的表格大小显示(5 个项目的总大小)。
  • &lt;td&gt; 元素使用固定宽度并从&lt;table&gt; 元素中删除width:100%
  • 是的,固定宽度可以解决我的问题,但我使用带 % 的宽度来适应更多屏幕尺寸。有什么建议吗?
  • 如果你想拥有 100% 的屏幕宽度,那么你可以在控制器中确保你的集合计数是 5 的倍数,如果不添加额外的“默认”thread 元素,这样当你生成//thread details here 它输出一个空字符串

标签: html asp.net-mvc razor view foreach


【解决方案1】:

如果我的项目小于 5,我通过在行中添加更多空白 &lt;td&gt; 来解决它。现在它显示为我想要的方式

<table style="width:100%;height:100%">
@{
    int count = 0;
    foreach (var thread in Model)
    {
        if (count % 5 == 0)
        {
            @:<tr>
        }
        <td style="width:20%">
            //thread details here
        </td>
        count++;
        if (count % 5 == 0)
        {
            @:</tr>
        }
    }
    while (count%5!=0)
    {
        <td></td>
        count++;
    }
    @:</tr>
}
</table>

【讨论】:

  • 我已经复制了您的代码,它会根据需要显示第二行(2 列占宽度的 40%,而不是 100%),所以我怀疑您可能有其他 css 干扰。您是否尝试过添加一个 &lt;thead&gt; 和一个包含 5 个 &lt;th&gt; 元素的 &lt;tr&gt; 并在 &lt;th&gt; 元素上设置宽度?另请注意,您应该使用 css,而不是这样的内联样式。
  • 感谢@StephenMuecke、&lt;thead&gt; 和 css 文件是很好的理想选择。
猜你喜欢
  • 2021-05-11
  • 2023-04-05
  • 1970-01-01
  • 2020-05-23
  • 2016-04-21
  • 1970-01-01
  • 1970-01-01
  • 2017-03-28
  • 2013-04-10
相关资源
最近更新 更多