2011-02-09 57 views
27

我在剃鬚刀中完成了部分視圖。當我運行它時,我得到以下錯誤 - 看起來Razor陷入了思考我正在編寫代碼的地方。「@」字符後出現意外的「foreach」關鍵字

「@」字符後出現意外的「foreach」關鍵字。一旦裏面的代碼,你不需要前綴,如「的foreach」與「@」

這裏構造是我的看法:

@model IEnumerable<SomeModel> 

<div> 
@using(Html.BeginForm("Update", "UserManagement", FormMethod.Post)) { 

    @Html.Hidden("UserId", ViewBag.UserId) 

@foreach(var link in Model) { 
    if(link.Linked) { 
     <input type="checkbox" name="userLinks" value="@link.Id" checked="checked" />@link.Description<br /> 
    } else { 
     <input type="checkbox" name="userLinks" value="@link.Id" />@link.Description<br />   
    } 
} 

} 
</div> 

回答

47

裏面你using塊,剃鬚刀期待C#來源,而不是HTML 。

因此,您應該在沒有@的情況下編寫foreach

在HTML標籤內部,Razor期待標記,因此您可以使用@

例如:

<div> 
    <!-- Markup goes here --> 
    @if (x) { 
     //Code goes here 
     if (y) { 
      //More code goes here 
      <div> 
       <!-- Markup goes here --> 
       @if (z) { } 
      </div> 
     } 
    } 
</div> 

你只需要一個@,如果你想要把代碼在那裏的預期標記,或者如果你想在任何地方寫輸出。

要將非標籤類標記置於期望代碼的位置,請使用@:<text>

+2

+1 - 我發現這是學習剃刀我的#1絆腳石。我的大腦似乎沒有立即認識到差異。做得更好,但我仍然發現自己寫錯了,然後不得不重新思考我的方式。 – 2011-02-09 15:27:13

2

我只是想添加到SLaks的答案,標記實際上並沒有干擾代碼部分只在標記內,並且一旦達到結束標記它將恢復到標記部分。

而且類似的東西在標記中也是一次,即使在代碼之後也需要使用@符號。

比方說你有以下:

@if(true) { 
     <span> 
      Markup section here, you need to include the @symbol 
      @if(1 = 1) 
      { 
      } 
      @if(2 = 2) @* The @ symbol here is required *@ 
      { 
      }     
     </span> 
     @: Code section back here, to output you need the "@:" symbol to display markup, although it is after the markup 
     if(false) @* Here the @ symbol isn't required *@ 
     { 
      some_statment; @* This will not be sent to the browser *@ 
      @display_someStament @* If we want to send it to the browser, 
        then we need the @ symbol even in the code section *@ 
     } 
}