The following code works great in Razor:
@if (!string.IsNullOrEmpty(Model.EmployeeNo))
{
@:(@Model.EmployeeNo)
}
However, I cannot work out how to display it as an Inline IF statement. The difficult part is that should the EmployeeNo value exist, it needs to be displayed wrapped in parenthesis.
I've tried lots of ways but can't get it to work. Latest attempt is
@if(!string.IsNullOrEmpty(Model.EmployeeNo ? @:(@Model.EmployeeNo) : string.Empty))
It looks like you're trying to do a ternary. You can only do that with valid C# code (you can't embed just any text or HTML inside. So, the following would work:
@(!string.IsNullOrEmpty(Model.EmployeeNo) ? "(" + Model.EmployeeNo + ")" : string.Empty)
Or, you could use string.Format
instead of concatenation:
string.Format("({0})", Model.EmployeeNo)
The point is that it's got to be actual code.
Also, with a ternary, you don't include the if
part, just in case you didn't notice in my code above. If you actually want to use an if
instead of a ternary, but still use just one line, that's fine, but you must still include the brackets:
@if (!string.IsNullOrEmpty(Model.EmployeeNo)) { @:(@Model.EmployeeNo) }
That's how Razor knows how to parse the if
block.