Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ternary operator in razor using a @Model (TimeSpan)?

I am trying to use the ternary operator in this piece of code, where Model.FirstTechSupportAssigneeElapseTime is of type TimeSpan?:

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

I have tried to implement the the ternary operator but I am failing miserably, the @'s everywhere are confusing me. Is it possible to have a the ternary operator in this scenario?

Thank you.

like image 645
Guillermo Sánchez Avatar asked Feb 06 '15 00:02

Guillermo Sánchez


2 Answers

Just keep in mind which scope you are in. Inside the if statement you do not need the @ because you are in c# scope. Inside of the conditional statement you are in razor scope, so you do need the @

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

This can also be done in using the ternary operator, assuming that elapsetime is a string (if it isn't there will be a conversion compilation error when the page loads)

<dt>Assigned In</dt>
<dd> 
@( Model.FirstTechSupportAssigneeElapseTime == null ? "N/A" : Model.FirstTechSupportAssigneeElapseTime.ToString() )
</dd>
like image 85
Travis J Avatar answered Nov 03 '22 09:11

Travis J


<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>
like image 29
JohnLBevan Avatar answered Nov 03 '22 08:11

JohnLBevan