How to close/reopen tag inside of if statement

asp.net-mvc, c#, razor, visual-studio-2012

Solution

You can use `@:` to explicitly define content. The following does not give compile errors on my system:

<div class="list-container">
    @{
        int i = 0;   

        @:<ul>
            @foreach (var item in Model.Items)
        {
            if (i % 8 == 0)
            {
        @:</ul>
        @:<ul>
            }

        <li>@item.ContentItem.Title.Value</li>

            i++;
        }
        @:</ul>
    }
</div>

Note: You also have incorrect comment syntax in your post, but I'm assuming that was just for the SO example.

Problem

I can't figure out what is wrong with this razor code. The IDE is telling me that my first `<ul>` doesn't have a matching end tag. It also says that the end tag doesn't have a matching beginning tag. It also doesn't recognize several lines as C# code and instead treats it as regular text. The IDE complaints are in comments on the offending lines. ``` <div class="list-container"> @{ int i = 0; <ul> //no matching ending tag @foreach (var item in Model.Items) { if (i % 8 == 0) { </ul> //no matching start tag <ul> //"Text is not allowed between the opening and closing tags for element ul" } //IDE doesn't recognize this closing brace as code... see it as text <li>@item.ContentItem.Title.Value</li> i++; //IDE doesn't recognize this closing brace as code... see it as text } //IDE doesn't recognize this closing brace as code... see it as text </ul> } </div> ``` When the view is executed, I get the compilation error you'd expect when you leave off a `}`: "The code block is missing a closing "}" character. " As soon as I remove the `</ul><ul>` from inside the `if` statement, the view compiles and executes. What's interesting is when I click on one of the `ul` tags, the correct starting or ending tag is also highlighted. Clearly I've done something wrong. Am I not using Razor correctly?

Original source