Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 777
sazr Avatar asked Jul 20 '15 04:07

sazr


People also ask

Can we use if condition in HTML?

Conditional Statements Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

Can HTML be embedded inside PHP if statement?

Yes, HTML can be embedded inside an 'if' statement with the help of PHP.

How can I write HTML code inside PHP?

Step 1: Firstly, we have to type the Html code in any text editor or open the existing Html file in the text editor in which we want to use the PHP. Step 2: Now, we have to place the cursor in any tag of the <body> tag where we want to add the code of PHP. And, then we have to type the start and end tag of PHP.

Can you put an if statement inside an if statement PHP?

We can use if statements inside if statements. These statements are called Nested If Statements.


1 Answers

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;
}
like image 85
Rowan Freeman Avatar answered Oct 12 '22 02:10

Rowan Freeman