How to make Razor inline code in some HTML?

What I want to do:

<div class='duck@if (this.Model.quacker) { -noisy }'>quack</div>

t. either

<div class='duck'>quack</div>

or

<div class='duck-noisy'>quack</div>

However, I cannot get the syntax correctly. I tried @:-noisybut generated errors like

Make sure you have the appropriate "}" character for all the "{" characters inside this block

I also tried @: - noisy @, but the same error. What should I do?

+5
source share
3 answers

The <text> element will go back to HTML. Like this:

<div class='duck@if (this.Model.quacker) { <text>-noisy</text> }'>quack</div>
+5
source

do the following:

@{
    var poo = string.Format("{0}{1}", "duck", (this.Model.quacker) ? "-noisy" : "");
}

<div class='@poo'>quack</div>

UPDATE

Below is the best solution:

<div class='@("duck")@if(this.Model.quacker){<text>-noisy</text>}'>quack</div>
+1
source

<div @if(this.Model.quacker) 
{
@:class='duck-noisy' 
}else{
@:class='duck'
}>quack</div>
+1

All Articles