Reputation: 2267
I am trying to check a boolean and then show an integer:
@( ViewBag.HaveBeenHere ? submission.DurationInMonths )
I am getting an error:
CS1003: Syntax error, ':' expected
I know the : is for the else, but in this case I don't have an else.
When I add it like this:
@( ViewBag.HaveBeenHere ? submission.DurationInMonths : "" )
I get this error:
CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'string'
How do I do a shorthand if statement to check a boolean and display an integer in the view?
Upvotes: 3
Views: 6277
Reputation: 1479
You could do this if you wanted to keep the syntax:
@( ViewBag.HaveBeenHere ? submission.DurationInMonths.ToString() : "" )
Adding ToString()
will, of course, make the return types the same.
Upvotes: 11
Reputation: 223247
You don't. Simply use an if
statement.
@( if(ViewBag.HaveBeenHere) submission.DurationInMonths; )
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.
Upvotes: 2
Reputation: 48096
That short hand is for if-else so it just doesn't work here. You can just do;
@( if(ViewBag.HaveBeenHere) { submission.DurationInMonths; } )
and it's no longer. If you have a one liner you can just put it on the same line as the if
condition.
Upvotes: 5