Is there a way to terminate MVC Razor @: line?

2019-07-20 18:41发布

问题:

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.

回答1:

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> } />