c# - Razor View - @if 语句编译错误

标签 c# .net asp.net-mvc razor asp.net-mvc-5

由 Visual Studio 构建的 Razor View 包含一个“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>

我想有条件地呈现这些链接:

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

上面的代码在 Visual Studio 中似乎是正确的,但是执行会导致编译错误

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

你能指出问题出在哪里吗?该代码在语法上似乎是正确的。

最佳答案

一旦你闯入一个c# 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>

或者如 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>

另见 Combining Text, Markup, and Code in Code Blocks

关于c# - Razor View - @if 语句编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31773711/

相关文章:

c# - C#中两个数组的相关性

asp.net-mvc - 如何限制对 MVC 中 Controller 或文件夹的访问?

c# - 保持配置文件 ID 可通过应用程序访问

c# - 在 MVVM 中,ViewModel 或 Model 应该实现 INotifyPropertyChanged 吗?

c# - 创建目录 - 访问被拒绝

c# - TPL数据流优化

asp.net-mvc - Kendo MVC Grid 默认按多列排序失败

c# - DataBinding() 不适用于 Distinct()( Entity Framework )

c# - 使用 BackgroundWorker 更新 UI 而不会卡住......?

c# - WPF MVVM 应用程序中的启动画面