简体   繁体   中英

Razor views - @if statement compilation error

Razor views scaffolded by Visual Studio contains an "actions" element with links separated by pipe character ( | )

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

I would like to render those links conditionally:

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

The code above seems correct in Visual Studio, however execution results in an 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:} 

Can you please point me where is the problem? The code seems syntactially correct.

Once you break into ac# block, you must explicitly break out again. You can use the <text> tag to add one or more lines of literal text to the output in this case.

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

Or as John H mentioned, you can use the syntax @: to break out of the code block for single lines of text.

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

See also Combining Text, Markup, and Code in Code Blocks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM