Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 622
Derek Avatar asked Apr 29 '13 15:04

Derek


1 Answers

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

like image 185
Splendor Avatar answered Sep 29 '22 20:09

Splendor