Razor & nested loops

2019-08-10 06:11发布

问题:

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