【问题标题】:Razor views - @if statement compilation errorRazor 视图 - @if 语句编译错误
【发布时间】:2015-10-24 18:12:14
【问题描述】:

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

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

<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

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# .net asp.net-mvc razor asp.net-mvc-5


    【解决方案1】:

    一旦你闯入一个 c# 块,你必须再次明确地闯入。在这种情况下,您可以使用&lt;text&gt; 标签在输出中添加一行或多行文字。

    <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

    【讨论】:

    • 你是对的,但有一种更简单的方法。 &lt;text&gt; |&lt;/text&gt;可以改成:@:|,效果一样。
    • @JohnH - 感谢您的提示!
    • 谢谢!您能否向我提供一个文档链接,该链接描述了它的工作原理以及为什么需要 &lt;text&gt; 或 @: 表达式?看起来有点丑陋,但显然这就是要走的路..
    • 我添加了我的答案的链接。
    猜你喜欢
    • 1970-01-01
    • 2021-09-22
    • 2015-01-21
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    相关资源
    最近更新 更多