How can I create a horizontal table in a single foreach loop in MVC?
Is there any way, in ASP.Net MV开发者_StackOverflow社区C, 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 an IEnumerable<SomeObject>
:
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.
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>
You can definitely improve this by using span and css stylings.
Check the following mat it help you
<table class="table">
<tr>
<td>
<table>
<tr><td>Name</td></tr>
<tr><td>Item</td></tr>
<table>
</td>
<%
foreach (var item in Model)
{
%>
<td>
<table>
<tr><td><%= item.Name %></td></tr>
<tr><td><%= item.company %></td></tr>
<table>
</td>
<%
}
%>
</tr>
</table>
Note:-
No check though :)
Very old thread, but...
I've used the following (but was looking for a better approach when I came across this question)
Create a code block that loops through the objects and creates the HTML for each row in a variable, then output the variable.
The plus is you're only looping once and do not have nested tables (so things are more likely to line up) but the minus is the string manipulation of html.
Should probably use stringbuilder rather than string, but principle is the same.
@code
Dim tr1 As String = "<th>Name</th>"
Dim tr2 As String = "<th>Company</th>"
For Each thingy As object In Model
tr1 += "<th>" & thingy.Name & "</th>"
tr2 += "<th>" & thingy.Company & "</th>"
Next
End Code
@<table class="table table-condensed">
<tr>@Html.Raw(tr1)</tr>
<tr>@Html.Raw(tr2)</tr>
</table>
精彩评论