0

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>
4

1 回答 1

6

您不需要在 C# 代码部分中添加 @ :

@foreach (var tagGroup in @Model.TagGroups)

应该

@foreach (var tagGroup in Model.TagGroups)

var selectedTag = @Model.Respondent.Tags.Where(r => r.Id == (int)tag.Id);

应该

var selectedTag = Model.Respondent.Tags.Where(r => r.Id == (int)tag.Id);
于 2013-10-30T20:39:56.407 回答