我正在尝试将响应式设计应用到我的asp.net mvc 4应用程序中。我想循环遍历我的模型并每行呈现3个项目。每行都应该包裹在一个div中。结果应该看起来像这样:
<div class='ResponsiveWrapper'>
<div>
<!-- item1 -->
</div>
<div>
<!-- item2 -->
</div>
<div>
<!-- item3 -->
</div>
</div>
<div class='ResponsiveWrapper'>
<div>
<!-- item4 -->
...
为了实现这个目的,我正在尝试使用三元运算符:
@{ var i = 0; }
@foreach (var item in Model)
{
@Html.Raw(i == 0 ? Html.Encode("<div class='section group'>") : "")
<div>
//Responsive Content comes here
</div>
@Html.Raw(i == 2 ? Html.Encode("</div>") : "")
@(i<3 ? i++ : i=0)
}
现在我有2个问题:
1. 三目运算符应该呈现的HTML标记以纯文本形式出现。我尝试了不同组合的@Html.Raw和@Html.Encode以及字符串,但都没有成功。 2. 最后一个三目运算符似乎会呈现变量i的当前值。我该如何防止这种情况发生?
附加信息/代码说明:
逻辑已经很好了: - i变量是计数变量。 - 如果i = 0,我先呈现包装器的起始div标签,然后呈现当前的model.item。 - 如果i = 1,我只呈现当前的model.item。 - 如果i = 2,我先呈现当前的model.item,然后呈现结束div标签。
谢谢
更新:
MajoB和Chris Pratt的方法基本上都可以。由于MajoB的解决方案更详细,所以我选择了那个。 然而,我必须进行一些修改才能使其工作:
At the Controller, I had to assure, that a IList is being returned, rather than a IEnumberable
public ActionResult Index() { return View(db.leModel.ToList()); }
At the View, I had to change the signature (like 1., IList instead of IEnumerable)
@model IList<leProject.Models.leModel>
Various modifications at the razor code (otherwise it would throw me exceptions)
最终代码:
<div class="ResponsiveWrapper">
@for (var i = 0; i < Model.Count; i++)
{
// the lambda expression modelItem => item.leProperty did not work for some reason. So I had to replace the item with Model[i], which means, the following line is not neccessary
{ var item = Model[i]; }
<div>
@Html.DisplayFor(modelItem => Model[i].leProperty)
</div>
if ((i + 1) % 3 == 0 || i == (Model.Count - 1))
{
@:</div>
if (Model.Count + 1 - i >= 3)
{
@:<div class="ResponsiveWrapper">
}
}
}
谢谢大家:)
@(stuff)
告诉 Razor 输出内容。尝试使用@{stuff}
替代 :-) - Søren Lorentzen