Home > DeveloperSection > Forums > Ternary operator in razor using a @Model
Ankit Singh

Total Post:341

Points:2389
Posted on    February-05-2015 10:24 PM

 ASP.Net C#  Razor 
Ratings:


 1 Reply(s)
 830  View(s)
Rate this:

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.



Tanuj Kumar

Total Post:134

Points:940
Posted on    February-05-2015 10:51 PM


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>


Modified On Mar-15-2016 05:36:52 AM

Don't want to miss updates? Please click the below button!

Follow MindStick