如何使用@Model(TimeSpan)在剃刀中使用三元运算符?

时间:2015-02-06 00:00:44

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

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

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

我试图实现三元运算符,但我失败了,@的处处令我困惑。在这种情况下,是否可以拥有三元运算符?

谢谢。

2 个答案:

答案 0 :(得分:12)

请记住您所在的范围。在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>

答案 1 :(得分: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>
相关问题