How to use ternary operator in razor (specifically on HTML attributes)?
You should be able to use the @()
expression syntax:
<a class="@(User.Identity.IsAuthenticated ? "auth" : "anon")">My link here</a>
Addendum:
The important concept is that you are evaluating an expression in your Razor code. The best way to do this (if, for example, you are in a foreach loop) is using a generic method.
The syntax for calling a generic method in Razor is:
@(expression)
In this case, the expression is:
User.Identity.IsAuthenticated ? "auth" : "anon"
Therefore, the solution is:
@(User.Identity.IsAuthenticated ? "auth" : "anon")
This code can be used anywhere in Razor, not just for an html attribute.
See @Kyralessa 's comment for C# Razor Syntax Quick Reference (Phil Haack's blog).