我怎样才能在MVC一个foreach循环创建水平表? [英] How can I create a horizontal table in a single foreach loop in MVC?

查看:569
本文介绍了我怎样才能在MVC一个foreach循环创建水平表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法,在ASP.Net MVC,凝结以下code到一个单一的foreach循环?

Is there any way, in ASP.Net MVC, to condense the following code to a single foreach loop?

<table class="table">
    <tr>
        <td>
            Name
        </td>    
        <% 
        foreach (var item in Model) 
        {
         %>
            <td>
                <%= item.Name %>
            </td>
        <% 
        } 
        %>
    </tr>
    <tr>
        <td>
            Item
        </td>    
        <% 
        foreach (var item in Model) 
        {
         %>
            <td>
                <%= item.Company %>
            </td>
        <% 
        } 
        %>
    </tr>
</table>

如果模型是一个的IEnumerable&LT; SomeObject&GT;

public class SomeObject
{
   public virtual Name {get;set;}
   public virtual Company {get;set;}
}

这将输出一个表如下:

Name     |    Bob    |     Sam    |    Bill   |     Steve    |
Company  |  Builder  |   Fireman  |     MS    |     Apple    |

我知道我大概可以使用扩展方法写出来的每一行,但有可能使用单次迭代在模型建立的所有行?

I know I could probably use an extension method to write out each row, but is it possible to build all rows using a single iteration over the model?

这是从这个<一个一个遵循href=\"http://stackoverflow.com/questions/3006082/how-do-i-make-a-table-from-a-list-mvc/3006133\">question因为我不满意我接受的答案,不能相信我所提供的最佳解决方案。

This is a follow on from this question as I'm unhappy with my accepted answer and cannot believe I've provided the best solution.

推荐答案

如果您并不局限于使用纯表,那么这将为你工作。

If you are not restricted to using pure tables, then this would work for you.

<table class="table"> 
    <tr> 
        <th> 
             Name<br/>
             Item<br/>
        </th>     
        <%  
        foreach (var item in Model)  
        { 
         %> 
            <td> 
                  <%= Html.Encode(item.Name) %><br/>
                  <%= Html.Encode(item.company) %><br/>
            </td> 
        <%  
        }  
        %> 
    </tr> 
</table> 

您绝对可以通过使用范围和CSS花式改善这一点。

You can definitely improve this by using span and css stylings.

这篇关于我怎样才能在MVC一个foreach循环创建水平表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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