2013-10-30 130 views
0

我想通過剃刀中的模型循環一些代碼。MVC剃刀foreach拋出編譯錯誤

TagGroups是TagGroups(簡單)和標籤組成的標籤組的列表。然後我有一個應答者從這個標籤組中選擇了一個標籤,他的選擇存儲在他的應答者數據中。

   @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> 
       } 

問題是這會引發編譯錯誤?我甚至試圖在if selectedTag之前添加「@」,然後在代碼塊中說@不是必需的。

我想輸出看起來像這樣:

<optgroup label="NFC NORTH"> 
         <option selected="selected">Chicago Bears</option> 
         <option>Detroit Lions</option> 
         <option>Green Bay Packers</option> 
         <option>Minnesota Vikings</option> 
        </optgroup> 
+0

如果你有編譯錯誤,你應該張貼錯誤消息 –

+1

旁註:'Enumerable.Where'永遠不會返回空... –

回答

6

你並不需要添加C#代碼部分的內部@:

@foreach (var tagGroup in @Model.TagGroups) 

應該

@foreach (var tagGroup in Model.TagGroups) 

And

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

應該

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