C# 如何使用@Model(TimeSpan)在razor中使用三元运算符?
我试图在这段代码中使用三元运算符,其中C# 如何使用@Model(TimeSpan)在razor中使用三元运算符?,c#,asp.net,razor,ternary-operator,timespan,C#,Asp.net,Razor,Ternary Operator,Timespan,我试图在这段代码中使用三元运算符,其中Model.FirstTechSupportAssigneeLassTime的类型为TimeSpan?: <dt>Assigned In</dt> <dd> @if (@Model.FirstTechSupportAssigneeElapseTime == null) { @:N/A } else { @Model.FirstTechSupportAssigneeElapseTime } <
Model.FirstTechSupportAssigneeLassTime
的类型为TimeSpan?
:
<dt>Assigned In</dt>
<dd>
@if (@Model.FirstTechSupportAssigneeElapseTime == null)
{ @:N/A }
else
{ @Model.FirstTechSupportAssigneeElapseTime }
</dd>
在中分配
@如果(@Model.firstTechSupportAssigneeLassTime==null)
{@:不适用}
其他的
{@Model.firstTechSupportAssigneeLassTime}
我曾尝试实现三元运算符,但我失败得很惨,到处都是使我困惑的。在这种情况下,三元运算符是否可能有一个新的值
谢谢。已分配到
<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>
@(
Model.firstTechSupportAssigneeLassTime==null
“不适用”
:Model.firstTechSupportAssigneeLassTime.ToString()//根据@Guillermo Sánchez的评论,FirstTechSupportAssigneeLassTime的类型似乎是TimeSpan
//因此,添加了“.ToString()”,以确保if语句的所有部分都返回相同类型的数据。
)
请记住您所处的范围。在if语句中,您不需要@
,因为您在c#scope中。在条件语句中,您处于razor范围内,因此确实需要@
<dt>Assigned In</dt>
<dd>
@if (Model.FirstTechSupportAssigneeElapseTime == null)
{
@:N/A
}
else
{
@Model.FirstTechSupportAssigneeElapseTime
}
</dd>
在中分配
@如果(Model.firstTechSupportAssigneeLassTime==null)
{
@:不适用
}
其他的
{
@Model.FirstTechSupportAssigneeLassTime
}
这也可以通过使用三元运算符来实现,假设elapsetime是字符串(如果不是,则在加载页面时会出现转换编译错误)
在中分配
@(Model.firstTechSupportAssigneeLassTime==null?“不适用”:Model.firstTechSupportAssigneeLassTime.ToString()
我相信您必须使用()而不是{}来让示例工作。由于某种原因,此解决方案不起作用,编译错误返回:无法确定条件表达式的类型,因为'string'和'System.TimeSpan之间没有隐式转换,我也尝试了{}和()。抱歉;根据@NickAlbrecht的评论,更新了带有普通括号的代码。实际上,ElapseTime是一个时间跨度,它抱怨这个原因运算符??无法应用于TimeSpan和string。@GuillermoSánchez-如果在TimeSpan上使用.ToString()
,则??
可能无法正常工作(请参见我的编辑),它告诉我“操作符的左手应该是参考时间或可为空的时间”这很奇怪,因为EllapseTime声明是这样的:公共时间跨度?FirstTechSupportAssigneeLassTime{get;private set;}太好了,最后一个建议有效@(Model.FirstTechSupportAssigneeLassTime==null?“N/A”:Model.FirstTechSupportAssigneeLassTime.ToString()),非常感谢
<dt>Assigned In</dt>
<dd>
@( Model.FirstTechSupportAssigneeElapseTime == null ? "N/A" : Model.FirstTechSupportAssigneeElapseTime.ToString() )
</dd>