asp.net-mvcasp.net-mvc-4razoractionlinkshorthand-if

MVC4 Razor shorthand if


@{(int)Session["current"] == 1 ? Html.ActionLink("Home", "Index", "Home", new { @class = "selected" }) : Html.ActionLink("Home", "Index", "Home");}

When I use this code I get an error: CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

I don't think the ";" supposed to be at the end, but without it I get an error saying that it's missing. I've tried using the <%= %> syntax but that didn't work too.


Solution

  • @async has a great answer.

    J̶u̶s̶t̶ ̶t̶o̶ ̶l̶e̶t̶ ̶y̶o̶u̶ ̶k̶n̶o̶w̶,̶ ̶t̶h̶e̶ ̶e̶q̶u̶i̶v̶a̶l̶e̶n̶t̶ ̶f̶o̶r̶ ̶̶<̶%̶=̶ ̶%̶>̶̶ ̶i̶n̶ ̶r̶a̶z̶o̶r̶ ̶i̶s̶ ̶̶@̶(̶)̶̶,̶ ̶n̶o̶t̶ ̶̶@̶{̶}̶̶

    Edit: As @JeremyCook Pointed out, the equivalent for <%= %> is @Html.Raw(). However in your case since you are using Html helper, there is no need for escaping the html encode. So you can use @()

    So for your case you can simply replace the bracket (and remove ";") then it should work:

    @((int)Session["current"] == 1 ? 
        Html.ActionLink("Home", "Index", "Home", new { @class = "selected" }) :     
        Html.ActionLink("Home", "Index", "Home"))