Derek
Derek

Reputation: 5855

Nested if statement is confusing Razor

I'm trying to set up a dropdown menu that pulls from a Datatable. This works just fine for the first level of the menu.

Working code:

<ul class="dropdown-menu">
@foreach (System.Data.DataRow dr in menu.Rows)
{
    if (Level1 != dr["Level1"].ToString())
    {
        <li><a href="#">@dr["Level1"].ToString()</a></li>
        Level1 = @dr["Level1"].ToString();
    }
}
</ul>

The problem occurs when I try to add a nested if statement. If you put this code into Visual Studio you will notice that the closing bracket for the @foreach loop is not recognized by Razor.

Code breaks:

<ul class="dropdown-menu">
@foreach (System.Data.DataRow dr in menu.Rows)
{
    if (Level1 != dr["Level1"].ToString())
    {
        <li><a href="#">@dr["Level1"].ToString()</a></li>
        Level1 = @dr["Level1"].ToString();

        if (Level2 != dr["Level2"].ToString())
        {
            <li><a href="#">@dr["Level2"].ToString()</a></li>
            Level2 = @dr["Level2"].ToString();                                        
        } 
    }
} <!-- the issue is the bracket on this line -->
</ul>

Upvotes: 18

Views: 34156

Answers (3)

Brett Donald
Brett Donald

Reputation: 14107

As per this answer, if a line is being interpreted as markup instead of code, put @ in front of it. If a line is being interpreted as code instead of markup, put @: in front of it.

Upvotes: 2

David Rettenbacher
David Rettenbacher

Reputation: 5120

I don't think you need to write the @ in front of @dr[...] in the lines where you assign the value to LevelX

<ul class="dropdown-menu">
@foreach (System.Data.DataRow dr in menu.Rows)
{
    if (Level1 != dr["Level1"].ToString())
    {
        <li><a href="#">@dr["Level1"].ToString()</a></li>
        Level1 = dr["Level1"].ToString(); // no need here

        if (Level2 != dr["Level2"].ToString())
        {
            <li><a href="#">@dr["Level2"].ToString()</a></li>
            Level2 = dr["Level2"].ToString();     // and no need here                                   
        } 
    }
} <!-- the issue is the bracket on this line -->
</ul>

EDIT

To address the question, why the closing bracket is not recognized.

TL;DR
As you are again in code-region you do not need the @-sign.

Details
The <li>...</li> section defines a html-region, where text is interpreted as html.
Directly after the closing </li> the outer code-region is active again and text is interpreted as C#-code. Therefore an assignment to Level1 is possible. Adding an @-sign to dr here has the same consequences as in an "normal" cs-file:
It's a syntax-error.

Upvotes: 5

Splendor
Splendor

Reputation: 1396

You'll need to wrap the offending section in <text> tags. See this answer: https://stackoverflow.com/a/6099659/1451531

Upvotes: 15

Related Questions