【问题标题】:Combine an 'in-line IF' (C#) with response.write将 'in-line IF' (C#) 与 response.write 相结合
【发布时间】:2010-12-21 16:43:50
【问题描述】:

在传统的 C# 代码块中:

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

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

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

谢谢

【问题讨论】:

  • 为了将来参考,它经常被称为“三元 if 运算符”。
  • @Greg:它实际上被称为条件运算符。 msdn.microsoft.com/en-us/library/ty67wk28.aspx
  • @Luke 公平地说,Greg 我看到它作为三元运算符引用的次数比条件运算符要多。在谈论 if 语句时,通常会引用条件。
  • @Luke:实际名称和经常使用的“事实上”名称通常不同。 :) 如果我想与人交流,我更有可能将“#”称为“井号”或“数字符号”而不是“八字”。
  • 我听说他们称之为“紧凑的 ifs”——“可怕的事情——让狡猾的开源变得更加丑陋!

标签: c# asp.net-mvc conditional-operator


【解决方案1】:

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

标记扩展的一个有趣的方面是它可以在标签的属性中使用,而其他两种形式(

【讨论】:

  • 非常感谢您为列出不同的标记标签所做的额外努力 - 您能否扩展以包含“#”的示例?
  • 据我所知,您可以使用您在标签属性中提到的三个&lt;% %&gt; 变体中的任何一个。为什么它会仅限于其中之一?除非您仅引用具有 runat="server" 属性的标签...
  • 我应该更清楚。 runat="server" 标签不支持 . 内扩展这些
  • 谢谢。看起来他想要 但正在使用 ,我也是。
【解决方案2】:
<%=
    (Discount > 0)
        ? "$" + Html.Encode(discountDto.Discount.FlatOff.ToString("#,###."))
        : ""
%>

【讨论】:

    【解决方案3】:

    Put Response.Write 围绕整个 ?:-operation:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多