1

How to escape quotes inside .cshtml file. I using razor mvc. I using If inside foreach

@for (int i = 1; i <= 4; i++)
{
    <div @(i == 1 ? "class=\"tab-pane active\"" : "class=tab-pane")>
    </div>
}

I using slash to escape quote but not working well.

The result <div class="&quot;tab-pane" active&quot;=""></div>

I want the result if for 1 will be <div class="tab-pane active"></div>

Stfvns
  • 1,001
  • 5
  • 16
  • 42

2 Answers2

2

You really should just insert/print/encode what you need, and not try to escape everything. Also less code, you don't have to repeat classes.. nice and DRY.

@for (int i = 1; i <= 4; i++)
{
  var active = i == 1 ? "active" : string.Empty;
  <div class="tab-pane @active">
  </div>
}

And it's much more readable and maintainable.

Output:

  <div class="tab-pane active">
  </div>
  <div class="tab-pane ">
  </div>
  <div class="tab-pane ">
  </div>
  <div class="tab-pane ">
  </div>
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
2

Just use ternary operator inside the class attribute, no need to repeat it twice:

@for (int i = 1; i <= 4; i++)
{
    <div class="@(i == 1 ? "tab-pane active" : "tab-pane")">
    </div>
}

Reference: How to use ternary operator in razor (specifically on HTML attributes)?

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61