With the WebForms view engine, I'll commonly use the ternary operator for very simple conditionals, especially within HTML attributes. For example:
<a class="<%=User.Identity.IsAuthenticated ? "auth" : "anon" %>">My link here</a>
The above code will give the <a>
tag a class of auth
or anon
depending on whether the user is authenticated.
What is the equivalent syntax with the Razor view engine? Because Razor requires HTML tags to "know" when to jump in and out of code and markup, I'm currently stuck with the following:
@if(User.Identity.IsAuthenticated) { <a class="auth">My link here</a> }
else { <a class="anon">My link here</a> }
This is, to put it mildly, terrible.
I would love to do something like this, but am struggling to understand how in Razor:
<a class="@=User.Identity.IsAuthenticated ? "auth" : "anon";">My link here</a>
--
Update:
In the meantime, I've created this HtmlHelper:
public static MvcHtmlString Conditional(this HtmlHelper html, Boolean condition, String ifTrue, String ifFalse)
{
return MvcHtmlString.Create(condition ? ifTrue : ifFalse);
}
which can be called like this from Razor:
<a class="@Html.Conditional(User.Identity.IsAuthenticated, "auth", "anon")">My link here</a>
Still, I am hoping there's a way to use the ternary operator without falling back to wrapping it in an extension method.
You should be able to use the
@()
expression syntax:I don't have Razor installed, though, so I could be wrong.
A simpler version, for easy eyes!
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:
In this case, the expression is:
Therefore, the solution is:
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).
in my problem I want the text of anchor
<a>text</a>
inside my view to be based on some value and that text is retrieved formApp string Resources
so, this
@()
is the solutionif the text is not from
App string Resources
use thisFor those of you who use ASP.net with VB razor the ternary operator is also possible.
It must be, as well, inside a razor expression:
and the ternary operator works as follows:
The same code example shown here with VB razor looks like this:
Note: when writing a TextExpression remember that Boolean symbols are not the same between C# and VB.
You can also use this method:
Try this .. Good luck Thanks.