简体   繁体   中英

Shorthand If without else in Razor view (ASP.NET MVC4)

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?

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.

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.

You don't. Simply use an if statement.

@( if(ViewBag.HaveBeenHere) submission.DurationInMonths; )

Conditional operator

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM