2013-12-10 40 views
3

我现在正在编写一些非常差的代码,甚至在我保存之前,我希望得到一些改进它的输入。我试图建立一个有三个单元格到每一行的HTML表格。如果集合有5个项目,那么它应该呈现为两行。在循环/ foreach MVC视图中动态生成表格

我写的代码目前为止我看不到很强大,需要不断的维护,但我不确定其他工具/方法来完成任务。

<table> 
    @foreach (VideosModel item in Model) 
    { 
     if (cellCount == 0 || cellCount == 3) 
     { 
      @Html.Raw("<tr>") 
     } 
      <td style="padding:0px 20px;"> 
       @item.VideoTitle <br /> 
       <a href="@item.VideoUrl" target="_blank"> 
        <img src="../../.../Video.jpg" /> <br /> 
       </a> 
       @item.VideoDescription 
       <br /> 
      </td> 

     cellCount++; 

     if (cellCount == 3 || cellCount == 6) 
     { 
      @Html.Raw("</tr>") 
     } 

     if (cellCount > 3) { cellCount = 0; } 
    } 
</table> 
+0

对于初学者来说,也没有必要有''包裹在一个'@ Html.Raw()' –

+0

当我没有包裹在原始的时候,我得到错误,如果然后关闭大括号没有找到。如此处所述:http://forums.asp.net/t/1654550.aspx – GPGVM

回答

8

你应该使用模考虑,而不是cellCount的值进行比较,以0,3或6:

<table> 
    @foreach (VideosModel item in Model) 
    { 
     if (cellCount % 3 == 0) 
     { 
      @:<tr> 
     } 
      <td style="padding:0px 20px;"> 
       @item.VideoTitle <br /> 
       <a href="@item.VideoUrl" target="_blank"> 
        <img src="../../.../Video.jpg" /> 
       </a><br /> 
       @item.VideoDescription 
       <br /> 
      </td> 

     cellCount++; 

     if (cellCount % 3 == 0) 
     { 
      @:</tr> 
     } 
    } 
</table> 
+0

@是什么?我不知道它和Googling @:或MVC @:返回nada。 – GPGVM

+0

与''相同的东西'http://weblogs.asp.net/scottgu/archive/2010/12/15/asp-net-mvc-3-razor-s-and-lt-text-gt-syntax的.aspx –