1
@{(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.

user3461434
  • 174
  • 1
  • 12

2 Answers2

5

You can do it like this

@Html.ActionLink("Pradžia", "Index", "Home", null, new { @class = (int)Session["current"] == 1 ? "selected" : "" })
nomad
  • 4,196
  • 4
  • 38
  • 55
  • Thank you, it's working. And you don't need the semicolon at the end. I noticed that it adds "?Length=4" at the end of the link now. What is that about? – user3461434 Apr 17 '14 at 14:31
  • 1
    Updated the answer with correct overload for Html.ActionLink() – nomad Apr 17 '14 at 14:34
  • Could you quickly explain why do we need the "null"? – user3461434 Apr 17 '14 at 14:38
  • 1
    Because if you use four parameters they are interpreted as `linkText`, `actionName`, `routeValues` and `htmlAttributes`. In original code "Home" is not correct value for `routeValues`. When you have five parameters they are interpreted as `linkText`, `actionName`, `controllerName`, `routeValues` and `htmlAttributes`. And here I used `null` for `routeValues`. – nomad Apr 17 '14 at 14:43
  • 1
    You can use Visual Studio's intellisense to see the overloads or go here: http://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-US&k=k%28System.Web.Mvc.Html.LinkExtensions.ActionLink%29;k%28TargetFrameworkMoniker-.NETFramework – nomad Apr 17 '14 at 14:44
  • I see. Thanks for your trouble! :) – user3461434 Apr 17 '14 at 14:47
2

@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"))
tweray
  • 961
  • 10
  • 18
  • Thanks! I might use this version, just to not fill my html with empty attributes. – user3461434 Apr 17 '14 at 14:41
  • 3
    The equivalent of `` in Razor is `@Html.Raw()`. `@()` is equivalent to the newer `` syntax in WebForms in that it automatically HTML encodes your output. – Jeremy Cook Apr 17 '14 at 15:05
  • @JeremyCook yes you are right. I forgot the diff in encoding. Thanks for pointing it out. – tweray Apr 17 '14 at 16:12