How to set html attributes using when Razor?
In the below code, I'd like to set the class attribute of element if "Succeeded" property of the current model is true.
<tbody>
@foreach (CharlieTestRunViewModel charlieTestRunViewModel in Model)
{
<tr class="@if([email protected]){'trFailedTestRun'}">
<td>
@charlieTestRunViewModel.Succeeded
</td>
</tr>
}
</tbody>
But it doesn't work.
How to achieve this?
Thanks
What about using the conditional operator:
<tr class="@(!charlieTestRunViewModel.Succeeded ? "trFailedTestRun" : "")">
With if:
<tr class="@if([email protected]){<text>trFailedTestRun</text>}">
I find using razor helper most elegant
@helper ClassIf(bool condition, string className)
{
if (condition)
{
@className
}
}
and use it like
<tr class="@MyHelpers.ClassIf(charlieTestRunViewModel.Succeeded, "trFailedTestRun")">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With