6

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;
}
2
  • As @RowanFreeman has indicated, escaping the HTML with @: is one way around this. If you are able to provide more context about what you're doing (what is your data, what is your desired markup result), I'd bet someone could come up with a solution that didn't involve having to worry about this. Commented Jul 20, 2015 at 4:16
  • Another option would be to connect the end div to the start div, and vice versa. The code excerpt given is a bit anti pattern from where I come from as you are splitting a div at a at seemingly random place. Commented Jul 20, 2015 at 5:15

3 Answers 3

14

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

i use This syntax :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.