Razor视图 - @if语句编译错误

Mar*_*mro 3 .net c# asp.net-mvc razor asp.net-mvc-5

由Visual Studio构建的Razor视图包含一个"actions"元素,其链接由管道符(|)分隔

<td>
   @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
   @Html.ActionLink("Details", "Details", new { id = item.Id }) |
   @Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
Run Code Online (Sandbox Code Playgroud)

我想有条件地渲染这些链接:

<td>
    @if (item.IsSuccess)
    {
        @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
        @Html.ActionLink("Details", "Details", new { id = item.Id }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.Id })
    }
</td>
Run Code Online (Sandbox Code Playgroud)

上面的代码在Visual Studio中似乎是正确的,但是执行会产生一个 Compilation Error

Compilation Error
Description: An error occurred during the compilation of a resource required    
to service this request. Please review the following specific error details and
modify your source code appropriately.

Compiler Error Message: CS1513: Expected sign }.

Source Error:


Line 491:        }
Line 492:    }
Line 493:}
Run Code Online (Sandbox Code Playgroud)

你能指点我问题在哪里吗?代码似乎是语法正确的.

Nig*_*888 5

一旦你进入ac#block,你必须再次明确地突破.<text>在这种情况下,您可以使用标记向输出添加一行或多行文字文本.

<td>
    @if (item.IsSuccess)
    {
        @Html.ActionLink("Edit", "Edit", new { id = item.Id })<text> |</text>
        @Html.ActionLink("Details", "Details", new { id = item.Id })<text> |</text>
        @Html.ActionLink("Delete", "Delete", new { id = item.Id })
    }
</td>
Run Code Online (Sandbox Code Playgroud)

或者正如John H所提到的,您可以使用语法@:来突破单行文本的代码块.

<td>
    @if (item.IsSuccess)
    {
        @Html.ActionLink("Edit", "Edit", new { id = item.Id })@: |
        @Html.ActionLink("Details", "Details", new { id = item.Id })@: |
        @Html.ActionLink("Delete", "Delete", new { id = item.Id })
    }
</td>
Run Code Online (Sandbox Code Playgroud)

另请参见在代码块中组合文本,标记和代码

  • 你是对的,但有一种更简单的方法.`<text> | </ text>`可以更改为:`@:|`,它将具有相同的效果. (4认同)