【问题标题】:How to use ternary operator in razor using a @Model (TimeSpan)?如何使用@Model(TimeSpan)在剃须刀中使用三元运算符?
【发布时间】:2015-04-06 00:54:20
【问题描述】:

我正在尝试在这段代码中使用三元运算符,其中Model.FirstTechSupportAssigneeElapseTime 的类型为TimeSpan?

<dt>Assigned In</dt>
<dd> 
@if (@Model.FirstTechSupportAssigneeElapseTime == null)
     { @:N/A } 
else 
     { @Model.FirstTechSupportAssigneeElapseTime } 
</dd>

我尝试实现三元运算符,但失败得很惨,@ 无处不在让我感到困惑。在这种情况下是否可以使用三元运算符?

谢谢。

【问题讨论】:

标签: c# asp.net razor ternary-operator timespan


【解决方案1】:
<dt>Assigned In</dt>
<dd> 
    @(
        Model.FirstTechSupportAssigneeElapseTime == null 
        ? "N/A" 
        : Model.FirstTechSupportAssigneeElapseTime.ToString()  //per @Guillermo Sánchez's comment, it seems that FirstTechSupportAssigneeElapseTime is of type TimeSpan
                                                               //therefore the `.ToString()` was added to ensure that all parts of the if statement return data of the same type.
    )  
</dd>

【讨论】:

  • 我相信您必须使用 () 而不是 {} 才能使您的示例正常工作。
  • 由于某种原因此解决方案不起作用,编译错误返回:无法确定条件表达式的类型,因为'string'和'System.TimeSpan之间没有隐式转换,我已经尝试使用{ } 和 () 也是如此。
  • 道歉;根据@NickAlbrecht 的评论更新了带有常规括号的代码。
【解决方案2】:

请记住您在哪个范围内。在 if 语句中,您不需要 @,因为您在 c# 范围内。在条件语句内部,您处于剃刀范围内,因此您确实需要 @

<dt>Assigned In</dt>
<dd> 
@if (Model.FirstTechSupportAssigneeElapseTime == null)
{ 
    @:N/A 
} 
else 
{
    @Model.FirstTechSupportAssigneeElapseTime
} 
</dd>

这也可以通过使用三元运算符来完成,假设 elapsetime 是一个字符串(如果不是,页面加载时会出现转换编译错误)

<dt>Assigned In</dt>
<dd> 
@( Model.FirstTechSupportAssigneeElapseTime == null ? "N/A" : Model.FirstTechSupportAssigneeElapseTime.ToString() )
</dd>

【讨论】:

  • 实际上 ElapseTime 是一个 TimeSpan 并且它抱怨这个原因 Operator ??不能应用于 TimeSpan 和字符串。
  • @GuillermoSánchez - ?? 可能无法正常工作,如果您在时间跨度上使用 .ToString(),您仍然可以使用三元运算符(请参阅我的编辑)
  • 它告诉我“?? 运算符的左手应该是参考时间或可为空的时间”这很奇怪,因为 EllapseTime 声明是这样的:public TimeSpan? FirstTechSupportAssigneeElapseTime { get;私人套装; }
  • 太好了,最后的建议奏效了@( Model.FirstTechSupportAssigneeElapseTime == null ? "N/A" : Model.FirstTechSupportAssigneeElapseTime.ToString() ),非常感谢
猜你喜欢
  • 2011-05-04
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
  • 2016-07-21
  • 2014-03-09
  • 2020-04-15
  • 2015-08-12
  • 1970-01-01
相关资源
最近更新 更多