Razor code blocks are not being recognized

IoEbi 20 Reputation points
2023-08-28T10:48:06.5333333+00:00

I'm having trouble with Razor code blocks.

I've confirmed that inline Razor syntax works without any issues.

However, I'm trying to generate HTML tags within a code block while processing loops and conditions.

As shown in the screenshot, it seems that foreach and if are not being recognized as Razor syntax.

What could be the cause of this issue?

Environment:MVC Core, .net6, VisualStudio2022

171132

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | ASP.NET | Other
{count} votes

Answer accepted by question author
  1. Bruce (SqlWork.com) 82,061 Reputation points Volunteer Moderator
    2023-08-28T17:50:37.56+00:00

    please read and learn the razor syntax. razor syntax is a template language. when in razor mode the @ is used to switch to c# code mode. when in c# mode, a razor block (<tag>) converts back to razor mode.

    @{ // define a c# code block
       var foo = "bar";
       <div> now in razor mode to add code need to go back to c# mode
       @if (foo == "bar")
       {
           // in c# mode
           <text>back in razor mode</text>
       }
       </div>
    }
    

    razor also parses the razor tags into a single expression. the tag must be complete. the tag can wrap code blocks and expressions, but can not span code blocks.

    valid:

    <div>
       @if (...) {
          ...
       } else {
          ...
       }
    </div>
    

    invalid:

       @if (...) {
          // tag must be complete before returning to the if code context
          <div>
       } else {
          </div>
       }
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.