views:

998

answers:

3

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

+9  A: 
<%=
    (Discount > 0)
        ? "$" + Html.Encode(discountDto.Discount.FlatOff.ToString("#,###."))
        : ""
%>
LukeH
+3  A: 

Put Response.Write around the whole ?:-operation:

<% Response.Write( Discount > 0 ? "$" + Html.Encode(discountDto.Discount.FlatOff.ToString("#,###.") : "" ) %>
Jan Aagaard
+8  A: 

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.

LBushkin
very much appreciate the extra effort to list different markup tags - could you expand to include an example of the "#"?
justSteve
As far as I'm aware, you can use any of the three `<% %>` variations you mentioned inside a tag attribute. Why would it be restricted to only one of them? Unless you were referring only to tags with the `runat="server"` attribute...
Joel Mueller
I should have been clearer. `runat="server"` tags don't support the <%, <%= markup expansions. However, there are exception even to this - for example meta tags do expand these inside <head>.
LBushkin