2

Consider this example:

<input type="checkbox" @if (flag) { @: checked } />

The problem is that the } /> is conceived by the Razor engine as part of the output string.

I've tried to use parenthesis but no luck.

Is there a way to terminate the @: operator in same line, or I'll have to split it to other line / use ternary operator?

Update

A very common use-case of my request can be adding a class if a value is true:

<div class='container @(active ? "active")'/>

So if the : of the ternary operator isn't present, it treats it treats it as a unary if operator, but that's just a wish...

Here's my suggestion on C# UserVoice.

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
  • possible duplicate of [How to use ternary operator in razor (specifically on HTML attributes)?](http://stackoverflow.com/questions/4091831/how-to-use-ternary-operator-in-razor-specifically-on-html-attributes) – Sani Huttunen Mar 17 '15 at 02:13
  • 1
    @SaniHuttunen Nope. Looks like you haven't even bothered reading my post. As I stated in my post, I know about the ternary operator and how to use it but I do NOT prefer to use it, I only want to emit a string if flag is true, but I want to do nothing if it's not. – Shimmy Weitzhandler Mar 17 '15 at 02:17
  • `` could work (http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/ ) – Alexei Levenkov Mar 17 '15 at 02:18
  • @AlexeiLevenkov haha! that's awesome. Why not post as answer. – Shimmy Weitzhandler Mar 17 '15 at 02:20

1 Answers1

6

For single attribute you can use @value syntax, that also have special case for checkbox (see Razor quick reference ):

<input type="checkbox" checked="@flag" />

You also can use <text> syntax that provides explicit (instead of "up to end of the line") closing tag:

<input type="checkbox" @if (flag) { <text>checked</text> } />
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179