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>
You'll need to wrap the offending section in <text>
tags. See this answer: https://stackoverflow.com/a/6099659/1451531
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>
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.