“@”字符后出现意外的“foreach”关键字

我用剃刀做了部分观点。 当我运行它时,我得到了下面的错误 – 看起来Razor陷入了思考我正在编写代码的地方。

“@”字符后出现意外的“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> 

在您using块内,Razor期待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>

我只是想添加到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 *@ } }