Razor & nested loops

谁都会走 提交于 2019-12-11 10:44:34

问题


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>
    }
}

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>");
}

回答1:


@ 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>
}


来源:https://stackoverflow.com/questions/36037840/razor-nested-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!