sazr
sazr

Reputation: 25928

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

Upvotes: 6

Views: 7249

Answers (3)

E Business
E Business

Reputation: 5

i use This syntax :

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

Upvotes: 0

3dd
3dd

Reputation: 2530

You can also use @Html.Raw("YOUR HTML"); inside an if statement to add HTML code

Upvotes: 0

Rowan Freeman
Rowan Freeman

Reputation: 16348

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

Upvotes: 14

Related Questions