Developer
Developer

Reputation: 8636

Ternary operator in aspx page

Hi all I would like to use ternary operator in aspx page. I am having two public variables in my aspx.cs file as follows

public string currency = "INR";
public decimal amount = 100;

I would like to frame the html tags based on my currency, currently I am doing like this

<% if (currency != "INR")
  {%>
     <span>$<%=amount%></span>
  <%}
  else
  { %>
    <span<%=amount%></span>
  <%} %>

I would like to do it one line

<span><% if (currency != "INR") %> $ amout <% : %> </span>

But I am getting error as Invalid expression term ':' so can some one help me if this is possible

Upvotes: 2

Views: 8448

Answers (3)

Rahul Nikate
Rahul Nikate

Reputation: 6337

Remove if from expression

You need to provide one more value after :

<span><%= (currency != "INR" ? "" : "Rs.") + amount %></span>

Upvotes: 1

bytecode77
bytecode77

Reputation: 14820

A tenary operator works without an if. It looks as follows:

booleanExpression ? trueValue : falseValue

But you can't treat ASP.NET like PHP, so you will have to put this in one <% %> wrapper

<span><%= (currency != "INR" ? "$" : "") + amount %></span>

Upvotes: 4

Mark Rabjohn
Mark Rabjohn

Reputation: 1713

bytecode77's code looks really awkward. I'd suggest:

<span><%= (currency != "INR") ? amount : " " %></span>

Upvotes: 1

Related Questions