How to use ternary operator in razor (specifically on HTML attributes)?
Asked Answered
H

7

483

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.

Houstonhoustonia answered 3/11, 2010 at 21:24 Comment(4)
Just as a matter of "Best Practice" I believe you should be returning type IHtmlString with the method new HtmlString("Some stuff here"); for helpers etc...Mclendon
You make like #6982353Traylor
Please vote here.Hepatitis
Related: https://mcmap.net/q/81040/-asp-net-mvc-razor-ternarySmacker
K
916

You should be able to use the @() expression syntax:

<a class="@(User.Identity.IsAuthenticated ? "auth" : "anon")">My link here</a>
Krystenkrystin answered 3/11, 2010 at 22:22 Comment(4)
Here's a handy reference to Razor syntax: C# Razor Syntax Quick ReferenceBrocky
<a class=@(User.Identity.IsAuthenticated ? "auth" : "anon")>My link here</a>Complemental
Can I add && operator into this logics ?Ronn
also possible: <a class="btn btn-secondary @(item.ValidTo == null ? "disabled-button" : "")">Link</a>Fosdick
C
75

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).

Cabe answered 16/11, 2011 at 11:36 Comment(2)
just noticed your addendum after adding the similar comments to the main answer.Complemental
How is an expression a generic method?Minnesinger
G
31

A simpler version, for easy eyes!

@(true?"yes":"no")
Gpo answered 22/1, 2012 at 15:57 Comment(5)
that's not simpler. that's the same answer with different valuesJavierjavler
-1 Dave Rael is right, this is the same code with different valuesCuprous
This actually explain the ternary operator. So it's a good addiction to the solution that doesn't say where is the true and false in the condition.Ripp
I thought so. as developers we are allowed to have clear answers.. sometimes.Gpo
I find this answer much clearer to me. Thanks @MonstersXExpert
V
19

For 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:

@(Razor_Expression)

and the ternary operator works as follows:

If(BooleanTestExpression, "TruePart", "FalsePart")

The same code example shown here with VB razor looks like this:

<a class="@(If(User.Identity.IsAuthenticated, "auth", "anon"))">My link here</a>

Note: when writing a TextExpression remember that Boolean symbols are not the same between C# and VB.

Vyner answered 7/11, 2012 at 14:33 Comment(0)
S
6

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 form App string Resources

so, this @() is the solution

<a href='#'>
      @(Model.ID == 0 ? Resource_en.Back : Resource_en.Department_View_DescartChanges)
</a>

if the text is not from App string Resources use this

@(Model.ID == 0 ? "Back" :"Descart Changes")
Smallwood answered 17/8, 2016 at 7:19 Comment(0)
C
2

You can also use this method:

<input type="text" class="@(@mvccondition ? "true-class" : "false-class")">

Try this .. Good luck Thanks.

Caecum answered 22/11, 2016 at 7:54 Comment(1)
is there any need for adding @ with mvc condition? I don't think so, because @ has already been used at the start.Chapin
D
0

I have a field named IsActive in table rows that's True when an item has been deleted. This code applies a CSS class named strikethrough only to deleted items. You can see how it uses the C# Ternary Operator:

<tr class="@(@businesstypes.IsActive ? "" : "strikethrough")">
Debus answered 28/8, 2020 at 17:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.