停止Razor循环

时间:2014-10-21 08:43:58

标签: c# asp.net-mvc asp.net-mvc-3 razor razorengine

无论如何都要跟踪Razor循环,并在其中间采取一些操作,然后继续循环:

EG。我有这个:

@foreach (var item in Model)
{
     @Html.DisplayFor(modelItem => item.Assignee)
}

我想(伪):

@var halfway = Model.count / 2
@var count = 0

@foreach (var item in Model) until count == halfway
{
     @Html.DisplayFor(modelItem => item.Assignee)
}

// hear we've reached halfway through, so I want to change add some HTML to the screen      

<hr />

@foreach remainder (var item in Model) 
{
     @Html.DisplayFor(modelItem => item.Assignee)
}

感谢您的任何建议,

5 个答案:

答案 0 :(得分:4)

您可以在商品清单上使用LINQ:

@var halfway = Model.count / 2
@foreach (var item in Model.Take(halfway))
{
     @Html.DisplayFor(modelItem => item.Assignee)
}

// Do your thing
<hr />

@foreach remainder (var item in Model.Skip(halfway)) 
{
     @Html.DisplayFor(modelItem => item.Assignee)
}

答案 1 :(得分:3)

 @for(int i=0;i<= halfway ; i++)
 {
    @Html.DisplayFor(modelItem => item.Assignee)
 }

答案 2 :(得分:1)

我建议您使用for循环,而不是foreach循环,前提是您的模型支持它。然后你可以使用count作为迭代器,只检查count == halfway

答案 3 :(得分:1)

您可以将其作为单个循环进行操作并跟踪您的位置,当您到达中途点时,您可以显示其他html。

@{
    var halfway = Model.Count() / 2;
    var count = 0;
    var isHalfway = false;
}

@foreach (var item in Model) 
{
    if ((count >= halfway) && (!isHalfway))
    {
        isHalfway = true;
        <hr />
    }

    @Html.DisplayFor(modelItem => item.Assignee)
    count++;
}

另一种选择是使用Linq:

@foreach (var item in Model.Take(halfway))
{
    @Html.DisplayFor(modelItem => item.VideoCode)
}
<hr />
@foreach (var item in Model.Skip(halfway))
{
    @Html.DisplayFor(modelItem => item.VideoCode)
}

答案 4 :(得分:1)

稍短的选项

@{
    var halfway = Model.Count()/2;
    var count = 0;
}
@foreach (var item in Model)
{
    @Html.DisplayFor(modelItem => item.Assignee)
    if (count++ == halfway)
    {
        <p>Your html code</p>
    }
}