剃刀嵌套循环 [英] Razor & nested loops

查看:51
本文介绍了剃刀嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我才刚刚开始学习Razor,并对嵌套循环有疑问.

I am just started to learn Razor and have a question regarding nested loops.

它使用以下代码正确呈现所有内容

It renders everything correctly using the following code

@foreach (var group in Model.Groups)
{
    foreach (var item in group.Items)
    {
        <span>@item.Title</item>
    }
}

但是当我用"div"标签包装第二个foreach时却没有.它说在这种情况下item变量不存在.

but does not when I wrap the second foreach with "div" tags. It saying the item variable does not exist in that case.

@foreach (var group in Model.Groups)
{
    <div>
    foreach (var item in group.Items)
    {
        <span>@item.Title</item>
    }
    </div>
}

我使用下面的代码使其工作,但怀疑它是最佳解决方案

I made it work using the following code, but doubt it is the best solution

@foreach (var group in Model.Groups)
{
    @Html.Raw("<div>");
    foreach (var item in group.Items)
    {
        <span>@item.Title</item>
    }
    @Html.Raw("</div>");
}

推荐答案

@的意思是嘿,这里有一些代码."如果您退回到标记中,则需要提醒razor即将到来的代码.我相信你想要的是

@ means "hey, here's some code." If you drop back into markup, you need to remind razor that there's code coming. I believe what you want it is

@foreach (var group in Model.Groups)
{
    <div>
    @foreach (var item in group.Items)
    {
        <span>@item.Title</item>
    }
    </div>
}

这篇关于剃刀嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆