Search code examples
c#asp.net-mvcrazor

How to Include HTML inside If Statement


Why when I have certain HTML in my C# statements does Razor complain about invalid expressions and terms?

And how can I fix this?

For example; in my _layout.cshtml:

@if (Team.Id == ViewBag.TeamId)
{
    </div>
    <div class="row">
    &nbsp;
}

Solution

  • Razor actually tries to understand your HTML. Unfortunately it can't be highly intelligent and recognise dynamic code or code outside of the expression.

    Since

    </div>
    <div>
    

    is invalid HTML, it complains.

    You can avoid this problem by using @:

    This forces razor to bypass its "HTML recognition", and simply print whatever you're asking for.

    E.g.

    @if (Team.Id == ViewBag.TeamId)
    {
        @:</div>
        @:<div class="row">
        @:&nbsp;
    }