How can I create a horizontal table in a single foreach loop in MVC?
Posted
by GenericTypeTea
on Stack Overflow
See other posts from Stack Overflow
or by GenericTypeTea
Published on 2010-06-10T07:08:50Z
Indexed on
2010/06/10
7:12 UTC
Read the original article
Hit count: 306
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>
Where model is a simple object:
public class SomeObject
{
public virtual Name {get;set;}
public virtual Company {get;set;}
}
This would output a table as follows:
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?
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.
© Stack Overflow or respective owner