C# 在剃刀的foreach中混合html和代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18172794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mix of html and code in foreach in razor
提问by Max
I want to create bootstrap grid with row-fluid class. It is need to separate all nested div's with span4 class into blocks. So I want to have html like this:
我想用 row-fluid 类创建引导网格。需要将所有带有 span4 类的嵌套 div 分成块。所以我想要这样的 html:
<div class="row-fluid">
<div class="span4"></div>
<div class="span4"></div>
<div class="span4"></div>
</div>
<div class="row-fluid">
<div class="span4"></div>
<div class="span4"></div>
<div class="span4"></div>
</div>
And I have code in razor
我在剃刀里有代码
@{
int counter = 3;
}
@foreach (var config in Model)
{
@if (counter == 3)
{
<div class="row-fluid">
@counter = 0;
}
@Html.Partial("_ConfigBar", config)
@if (counter == 2)
{
</div>
}
@{counter++;}
}
Partial view just put div with span4 class, and there are nothing interesting.
局部视图只是把 div 与 span4 类,并没有什么有趣的。
But it didn't work. Can anyone point me what is wrong?
但它没有用。任何人都可以指出我有什么问题吗?
采纳答案by Digbyswift
Something like this should create what you need:
像这样的东西应该创建你需要的东西:
@{
int counter = 0;
foreach (var config in Model)
{
if (counter == 0)
{
@Html.Raw("<div class=\"row-fluid\">")
}
else if (counter > 0 && counter % 3 == 0 )
{
@Html.Raw("</div><div class=\"row-fluid\">")
}
@Html.Partial("_ConfigBar", config)
counter++;
}
@Html.Raw("</div>")
}
This will:
这会:
- create an opening div on the first loop
- close the current open div and open a new div on each 4th loop
- add a closing div once the looping is complete.
- 在第一个循环上创建一个开放的 div
- 关闭当前打开的 div 并在每个第 4 个循环中打开一个新的 div
- 循环完成后添加一个关闭 div。