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

时间:2015-08-02 15:56:29

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

Visual Studio支持的Razor视图包含一个"动作"链接由管道符(|

分隔的元素
<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:}
你能指出我问题在哪里吗?代码似乎在语法上是正确的。

2 个答案:

答案 0 :(得分:5)

一旦你进入c#块,你必须再次明确地突破。在这种情况下,您可以使用<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

答案 1 :(得分:0)

只需添加div标签

即可
@if (item.IsSuccess)
{ 
    <div>
    @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
    @Html.ActionLink("Details", "Details", new { id = item.Id }) |
    @Html.ActionLink("Delete", "Delete", new { id = item.Id })
    </div>
}