Lambda in Html.ActionLink using razor
what is the correct way to use Lambda in an ActionLink?
I'm trying this: @Html.ActionLink(item.PageName, "ContentPage", new { id = item.PageName }, new { @title = item.ToolTip, item.开发者_开发技巧Selected == 1 ? "class=selected" : "" })
but get an error for some reason,i can't figure out the correct syntax for it?
ThanksI don't know ActionLink, but seems that in this piece of code:
new { @title = item.ToolTip, item.Selected == 1 ? "class=selected" : "" }
you are declaring an anonimus type, whith a first field named "@title", but.... the second?!? Here we see an expression with a ternary operator, but it's return value isn't assigned to anything. You have to add an identifier and an assignement operator before "item.Selected":
new { @title = item.ToolTip, class = item.Selected == 1 ? "selected" : "" }
If a value of class="" is not valid, you could try to can put the entire object in ternary operator, like this:
item.Selected == 1 ? new { @title = ... } : new { @title = ..., class = "selected" }
But likely this will not work: the ternary operator will not be able to determine the result type (the two anonimous type have different signature). The only other way is to instantiate first the right anonimous object, using the "var" type, and then pass it to the metod. In any case there are no lambda expressions here. You should tag your answer with "anonimous types" instead of "lambda".
Have you tried:
@Html.ActionLink(item.PageName,"ContentPage",new { id = item.PageName },new { @title = item.ToolTip, selected = (item.Selected == 1) ? "class=selected" : "" })
(you were missing a HTML property name).
This is new anonymous type syntax rather than lambas, for lambdas with generic types you have to wrap an extra set of brackets around the statement.
精彩评论