ASP.NET MVC: use of @ in C# code block

2019-07-31 07:21发布

问题:

I'm a little bit confused with the use of @. In the following code I first wrote Html.ActionLink(...) instead of @Html.ActionLink(...) because I was in a if block (C# code). So, I would like to understand exactly when I do have to use @ and when I don´t have to use it.

<td width="32%" align="center">
     @if (Model.SeccionImpresos != null)
     {
           @Html.ActionLink("IMPRESOS", "Index", "Trabajo", null, null, "#impresos", new { id = Model.Id }, null);
     }
</td>

I appreaciate any help on this.

回答1:

@ has two uses:

  • It's used to start a code block (@if, @foreach, @{ ... }, etc) from a markup context (as opposed to from another code block)

  • It's used for code nuggets – expressions which are written to the output stream (@expression).

Writing Html.ActionLink without @ in a code block creates a normal method call that discards its result.