I’m trying to nest a foreach within an if/else using Razor, but am having some issues with Razor claiming I’m missing a closing bracket. The code is below, where I’ve noted the “else” that isn’t being syntax-highlighted by Visual Studio, which I’m guessing is where the issue lies:
@if (ViewBag.user.administrativeRole != null)
{
<select name="administrativeRole" id="administrativeRole" class="selectInput" disabled="disabled">
}
else // this else isn't syntax highlighted
{
<select name="administrativeRole" id="administrativeRole" class="selectInput">
@foreach (var role in ViewBag.roles)
{
if (ViewBag.user.administrativeRole != null && ViewBag.user.administrativeRole == role.superadmin)
{
<option value="@role.id" selected="selected">@role.name</option>
}
else
{
<option value="@role.id">@role.name</option>
}
}
}
</select>
which generates the following error:
The if block is missing a closing “}”
character. Make sure you have a
matching “}” character for all the
“{” characters within this block, and
that none of the “}” characters are
being interpreted as markup.
Line 58: @if (ViewBag.user.administrativeRole != null)
Line 59: {
Line 60: <select name="administrativeRole" id="administrativeRole" class="selectInput" disabled="disabled">
Any thoughts? I’m guessing I just borked the syntax a bit, as I’m new to Razor.
Your
</select>is in the wrong place.It needs to be after the second
}, at the same level as the<select>.Because it isn’t, Razor treats the last
}as markup rather than code, so the outerifis not closed.Also, you should call
Html.DropDowninstead.