首页 > 解决方案 > @: in a foreach loop doesn't work when it's between tags?

问题描述

I know that @: is for output a single line of content containing plain text or unmatched HTML tags;

If so , why do I get an error for :

( ":" is not valid at the start of a code block. Only identifiers, keywords, comments, "(" and "{" are valid.)

  @foreach (int line in new int[] { 0, 1 })
    {
        <span>
          @: aaaaa
        </span>
    }

While this run as expected :

@foreach (int line in new int[] { 0, 1 })
{
      @: aaaaa
}

标签: asp.net-mvc

解决方案


@: is used to mix text within a code block.

When you use the span tag or any other html elements, inside a C# code block, you are already mixing HTML tag and razor can properly parse and execute it. When you use @: inside an HTML element (non-code block), it is not even valid.

In short, you can use HTML elements inside a code block as wrapper to mix plaintext/html.

@foreach (int line in new int[] { 0, 1 })
{
    <div>Hello</div>
}

In razor, the @: tag produce the same result as the text tag when it comes to mixing plain text within a code block. The below will also produce same result as your second code block.

@foreach (int line in new int[] { 0, 1 })
{
    <text>aaa533</text>
}

推荐阅读