如何在 MVC 中的单个 foreach 循环中创建水平表?
在 ASP.Net MVC 中,有什么方法可以将以下代码压缩为单个 foreach 循环吗?
<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
:
public class SomeObject
{
public virtual Name {get;set;}
public virtual Company {get;set;}
}
这将输出一个表,如下所示:
Name | Bob | Sam | Bill | Steve |
Company | Builder | Fireman | MS | Apple |
我知道我可能可以使用扩展方法来写出每一行,但是是否可以使用单个方法构建所有行模型迭代?
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不限于使用纯表,那么这对您有用。
您绝对可以通过使用 span 和 css 样式来改进这一点。
If you are not restricted to using pure tables, then this would work for you.
You can definitely improve this by using span and css stylings.
检查以下垫子它可以帮助您
注意:-
Check the following mat it help you
Note:-
非常旧的线程,但是...
我使用了以下内容(但是当我遇到这个问题时正在寻找更好的方法)
创建一个循环遍历对象并为变量中的每一行创建 HTML 的代码块,然后输出变量。
优点是你只循环一次并且没有嵌套表(所以事情更有可能排列),但缺点是 html 的字符串操作。
可能应该使用 stringbuilder 而不是 string,但原理是相同的。
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.