18

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>
Derek
  • 5,137
  • 9
  • 28
  • 39

3 Answers3

15

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

Community
  • 1
  • 1
Splendor
  • 1,386
  • 6
  • 28
  • 62
5

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.

David Rettenbacher
  • 5,088
  • 2
  • 36
  • 45
  • He doesn't need them indeed, but this doesn't address the question. Thanks for the note though. – Lzh Apr 29 '13 at 16:06
2

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.

Community
  • 1
  • 1
Brett Donald
  • 6,745
  • 4
  • 23
  • 51