如何使用 @Model (TimeSpan) 在剃刀中使用三元运算符?
How to use ternary operator in razor using a @Model (TimeSpan)?
我正在尝试在这段代码中使用三元运算符,其中 Model.FirstTechSupportAssigneeElapseTime
的类型为 TimeSpan?
:
<dt>Assigned In</dt>
<dd>
@if (@Model.FirstTechSupportAssigneeElapseTime == null)
{ @:N/A }
else
{ @Model.FirstTechSupportAssigneeElapseTime }
</dd>
我曾尝试实现三元运算符,但失败得很惨,到处都是@,这让我很困惑。在这种情况下是否可以使用三元运算符?
谢谢。
<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>
请记住您在哪个范围内。在 if 语句中您不需要 @
因为您在 c# 范围内。在条件语句中,您处于剃刀范围内,因此您确实需要 @
<dt>Assigned In</dt>
<dd>
@if (Model.FirstTechSupportAssigneeElapseTime == null)
{
@:N/A
}
else
{
@Model.FirstTechSupportAssigneeElapseTime
}
</dd>
这也可以使用三元运算符来完成,假设elapstime是一个字符串(如果不是,则在页面加载时会出现转换编译错误)
<dt>Assigned In</dt>
<dd>
@( Model.FirstTechSupportAssigneeElapseTime == null ? "N/A" : Model.FirstTechSupportAssigneeElapseTime.ToString() )
</dd>
我正在尝试在这段代码中使用三元运算符,其中 Model.FirstTechSupportAssigneeElapseTime
的类型为 TimeSpan?
:
<dt>Assigned In</dt>
<dd>
@if (@Model.FirstTechSupportAssigneeElapseTime == null)
{ @:N/A }
else
{ @Model.FirstTechSupportAssigneeElapseTime }
</dd>
我曾尝试实现三元运算符,但失败得很惨,到处都是@,这让我很困惑。在这种情况下是否可以使用三元运算符?
谢谢。
<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>
请记住您在哪个范围内。在 if 语句中您不需要 @
因为您在 c# 范围内。在条件语句中,您处于剃刀范围内,因此您确实需要 @
<dt>Assigned In</dt>
<dd>
@if (Model.FirstTechSupportAssigneeElapseTime == null)
{
@:N/A
}
else
{
@Model.FirstTechSupportAssigneeElapseTime
}
</dd>
这也可以使用三元运算符来完成,假设elapstime是一个字符串(如果不是,则在页面加载时会出现转换编译错误)
<dt>Assigned In</dt>
<dd>
@( Model.FirstTechSupportAssigneeElapseTime == null ? "N/A" : Model.FirstTechSupportAssigneeElapseTime.ToString() )
</dd>