Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 270
Portman Avatar asked Nov 03 '10 21:11

Portman


People also ask

Can I use ternary operator in HTML?

The ternary operation that you have incorporated in your program, doesn't works for class or to be specific - HTML DOM. It can be done using AngularJS, as it provides a wonderful inbuilt directive knows as ng-class . Using this one can set the conditions, based on which one needs to apply the class .

What is ternary operator in HTML?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

How do you use a ternary operator example?

Example: C Ternary Operator Here, age >= 18 - test condition that checks if input value is greater or equal to 18. printf("You can vote") - expression1 that is executed if condition is true. printf("You cannot vote") - expression2 that is executed if condition is false.

What is Razor in HTML?

Razor is a markup syntax for embedding . NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension.


1 Answers

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

<a class="@(User.Identity.IsAuthenticated ? "auth" : "anon")">My link here</a> 
like image 119
David Brown Avatar answered Nov 01 '22 23:11

David Brown