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

asp.net-mvc, c#, conditional-operator

Solution

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.

Problem

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

Original source