So I have the following code in .net Razor:
<div id="menu_left" class="menu_item">
@foreach (var mainMenuItem in Model)
{
string link ="";
string nameLower = @mainMenuItem.ItemName.ToLower();
if (mainMenuItem.SubItem.Count() > 0)
{
link +="javascript:submenu('";
link += nameLower + "_dropdown";
link += "', 'dropdown_menu' );";
}
else
{
link = mainMenuItem.Link;
}
}
<a href="@link" class="menu_a">
<img src="@mainMenuItem.Image" class="menu_link" id="@mainMenuItem.ItemName.ToLower()" />
</a>
}
</div>
but when I try to run it, the .net compiler renders the line at the end of the if statement as an html literal rather than compiling it as code, as is shown by the following section from the compilation source:
Line 145: WriteLiteral(@" else
Line 146: {
Line 147: link = mainMenuItem.Link;
Line 148: }
Line 149: }
I have tried wrapping the entire thing in a @{} code block so it knows that it is code, but then the compiler seems to end the block on the wrong curly bracket, like the one at the end of the foreach loop.
I have seen other people on SO that have the same problem when there is html inside the 'if' statement, but there is no html inside of this block.
How do I get the rest of my code to render as code?
Remove @ from
@mainMenuItem.ItemName.ToLower();
You only need @ symbol, when you are starting c# code and when you are mixing it with html.
For example, in this case you will need @ symbol to render nameLower's value:
@foreach (var mainMenuItem in Model)
{
string link = "";
string nameLower = mainMenuItem.ItemName.ToLower();
<div>
some html
@nameLower
</div>
}