Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine an 'in-line IF' (C#) with response.write

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

like image 416
justSteve Avatar asked Nov 30 '09 15:11

justSteve


People also ask

Can IF statement have 2 conditions in C?

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.

Can you use && and || together?

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.

What does || mean in if statement?

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


2 Answers

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.

like image 161
LBushkin Avatar answered Sep 17 '22 23:09

LBushkin


<%=
    (Discount > 0)
        ? "$" + Html.Encode(discountDto.Discount.FlatOff.ToString("#,###."))
        : ""
%>
like image 45
LukeH Avatar answered Sep 21 '22 23:09

LukeH