2015-02-06 58 views
4

我试图使用三元运算在这一段代码,其中Model.FirstTechSupportAssigneeElapseTimeTimeSpan?类型:如何使用@Model(TimeSpan)在剃须刀中使用三元运算符?

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

我试图实现三元运算符,但我没有草草收场时,@的无处不在令我困惑。在这种情况下可以有三元运算符吗?

谢谢。

回答

11

只要记住你所在的范围。在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> 
+0

其实ElapseTime是一个TimeSpan,它对此抱怨操作符?不能应用于TimeSpan和字符串。 – 2015-02-06 00:23:54

+0

@GuillermoSánchez - 如果在时间范围内使用'.ToString()',那么''''''''''可能还不能很好地运行三元运算符(请参阅我的编辑) – 2015-02-06 00:25:10

+0

它告诉我“左手“operator shoild be reference or nullable time”这很奇怪,因为EllapseTime声明是这样的:public TimeSpan? FirstTechSupportAssigneeElapseTime {get;私人设置; } – 2015-02-06 00:28:42

4
<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> 
+1

我相信你必须用()而不是{}来让你的例子工作。 – 2015-02-06 00:14:29

+0

由于某种原因,此解决方案无效,编译错误返回:条件表达式的类型无法确定,因为'string'和'System.TimeSpan之间没有隐式转换,我也尝试过使用{}和()。 – 2015-02-06 00:18:56

+1

@NickAlbrecht不得不这样做,谢谢你们俩 – 2017-06-01 14:16:29