9

在传统的 C# 代码块中:

"myInt = (<condition> ? <true value> : <false value>)"

但是在我想有条件地响应的 .aspx 中使用呢?

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

多谢

4

3 回答 3

19

有必要了解 ASP.NET 模板标记处理中不同标记标记的含义:

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

因此,要发出三元表达式(错误条件运算符)的值,您可以使用:

<%= (condition) ? if-true : if-false %>

或者你可以写L

<% Response.Write( (condition) ? if-true : if-false ) %>

如果您使用的是数据绑定控件(例如中继器),则可以使用数据绑定格式来评估并发出结果:

<asp:Repeater runat='server' otherattributes='...'>
     <ItemTemplate>
          <div class='<%# Container.DataItem( condition ? if-true : if-false ) %>'>  content </div>
     </ItemTemplate>
 </asp:Repeater>

<%# %> 标记扩展的一个有趣的方面是它可以在标签的属性中使用,而其他两种形式(<% 和 <%=)只能在标签内容中使用(有一些特殊的情况例外)。上面的例子证明了这一点。

于 2009-11-30T16:09:34.113 回答
9
<%=
    (Discount > 0)
        ? "$" + Html.Encode(discountDto.Discount.FlatOff.ToString("#,###."))
        : ""
%>
于 2009-11-30T15:59:17.473 回答
3

将 Response.Write 放在整个 ?:-操作中:

<% Response.Write( Discount > 0 ? "$" + Html.Encode(discountDto.Discount.FlatOff.ToString("#,###.") : "" ) %>
于 2009-11-30T16:01:21.197 回答