Reputation: 7265
I am trying to loop through some code from my model in razor.
TagGroups is a list of TagGroups(easy) and Tags apart of that tag group. Then I have a respondent who has selected a tag out of this tag groups and his selection is stored inside of his respondent data.
@foreach (var tagGroup in @Model.TagGroups)
{
<optgroup label="@tagGroup.Name">
@foreach (var tag in tagGroup.Tags)
{
var selectedTag = @Model.Respondent.Tags.Where(r => r.Id == (int)tag.Id);
if (selectedTag != null)
{
<option selected="selected">@tag.Name</option>
}
else
{
<option>@tag.Name</option>
}
}
</optgroup>
}
Problem is that this throws a compilation error? I have even tried to add "@" before the if selectedTag which then says the @ is not necessary inside a block of code.
I want the output to look like so:
<optgroup label="NFC NORTH">
<option selected="selected">Chicago Bears</option>
<option>Detroit Lions</option>
<option>Green Bay Packers</option>
<option>Minnesota Vikings</option>
</optgroup>
Upvotes: 0
Views: 603
Reputation: 1143
You don't need to add a @ inside of C# code part:
@foreach (var tagGroup in @Model.TagGroups)
should be
@foreach (var tagGroup in Model.TagGroups)
And
var selectedTag = @Model.Respondent.Tags.Where(r => r.Id == (int)tag.Id);
should be
var selectedTag = Model.Respondent.Tags.Where(r => r.Id == (int)tag.Id);
Upvotes: 6