2011-02-09 27 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 *@ 
     } 
}