Razor View 动态表格行 [英] Razor View dynamic table rows

查看:26
本文介绍了Razor View 动态表格行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的视图中有一个表格,它将把模型中的 3 个元素放在每一行中.所以我打算这样做的方法是遍历模型并在 foreach 循环内部检查我设置的计数变量.如果 count mod 3 == 0 我会做一些类似 </tr><tr> 的事情来开始一个新行.这不是我想要的方式,因为我会在 <tr> 后面有一个 }.所以基本上我的问题是,我将如何根据模型中的元素在 razor 视图中创建一个动态表,其中每行有 3 个项目?

@{整数计数 = 0;<div><表格><tr>@foreach(模型中的 var 绘图){<td style="width:240px;margin-left:30px; margin-right:30px;"><img src="@Url.Action("GetImage", "Home", new { id = drawing.drw_ID })" alt="绘图"/></td>计数++;如果(计数%3==0){</tr><tr>}}</tr>

}

也许有一种我没有想到的更简单的方法

解决方案

如何使用两个循环 - 这将使您的文档设置得更好,并使其更具可读性.此外,它会处理如果行数不能被 3 整除时出现的问题:

<表格>@for(int i = 0; i <= (Model.Count - 1)/3; ++i) {<tr>for(int j = 0; j <3 && i + j

已编辑以反映您粘贴的代码.注意,这里假设模型实现了 IList 或一个数组

I want have a table in my view that is going to put 3 elements from my Model in each row. So the way I was going to do this is to loop through the model and inside of the foreach loop do a check on a count variable I have set up. If count mod 3 == 0 I would do something like </tr><tr> to start a new row. This isn't working the way I want it to because I would have a } following the <tr>. So basically my question is, how would I create a dynamic table inside of a razor view based on the elements in the model where each row has 3 items?

@{
int count = 0;
<div>
<table>
<tr>
@foreach (var drawing in Model)
{
   <td style="width:240px;margin-left:30px; margin-right:30px;">
   <img src="@Url.Action("GetImage", "Home", new { id = drawing.drw_ID })" alt="drawing" /> 
   </td>
   count++;
   if(count%3==0)
   {
      </tr>
      <tr>
   }
} 
</tr>
</table>
</div>
}

Maybe there is a much easier way of doing this that I am not thinking of

解决方案

How about using two loops - this will make your document be setup much more nicely and make it a bit more readable. Also, it takes care of the problems that occur if the number of rows is not divisible by three:

<div>
<table>
@for(int i = 0; i <= (Model.Count - 1) / 3; ++i) {
  <tr>
  for(int j = 0; j < 3 && i + j < Model.Count; ++j) {
    <td style="width:240px;margin-left:30px; margin-right:30px;">
      <img src="@Url.Action("GetImage", "Home", new { id = Model[i + j].drw_ID })" alt="drawing" /> 
    </td>
   }
   </tr>
}
</table>
</div>

Edited to reflect your pasted code. Note, this assumes the model implements IList or an array

这篇关于Razor View 动态表格行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆