in a conventional C# code block:
"myInt = (<condition> ? <true value> : <false value>)"
but what about use inside an .aspx where I want to response.write conditionally:
<% ( Discount > 0 ? Response.Write( "$" + Html.Encode(discountDto.Discount.FlatOff.ToString("#,###."): "")%>
mny thx
There can also be multiple conditions like in C if x occurs then execute p, else if condition y occurs execute q, else execute r. This condition of C else-if is one of the many ways of importing multiple conditions.
The logical operators && ("and") and || ("or") combine conditional expressions; the ! ("not") operator negates them. The ! has the highest precedence, then && , then || ; you will need parentheses to force a different order.
|| is a short circuit 'or' boolean operator. If the expression on the left hand side evaluates to true there is no need to evaluate the expression on the right as the condition has already been met.
It's worth understanding what the different markup tags mean within ASP.NET template markup processing:
<% expression %> - evaluates an expression in the underlying page language
<%= expression %> - short-hand for Response.Write() - expression is converted to a string and emitted
<%# expression %> - a databinding expression that allows markup to access the current value of a bound control
So to emit the value of a ternary expression (err conditional operator) you can either use:
<%= (condition) ? if-true : if-false %>
or you can writeL
<% Response.Write( (condition) ? if-true : if-false ) %>
If you were using databound control (like a repeater, for example), you could use the databinding format to evaluate and emit the result:
<asp:Repeater runat='server' otherattributes='...'>
<ItemTemplate>
<div class='<%# Container.DataItem( condition ? if-true : if-false ) %>'> content </div>
</ItemTemplate>
</asp:Repeater>
An interesting aspect of the <%# %> markup extension is that it can be used inside of attributes of a tag, whereas the other two forms (<% and <%=) can only be used in tag content (with a few special case exceptions). The example above demonstrates this.
<%=
(Discount > 0)
? "$" + Html.Encode(discountDto.Discount.FlatOff.ToString("#,###."))
: ""
%>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With