Is there a better way to dynamically add css to a razor than with @if ()

Is it possible to optimize class assignment in general? I have to do this in many different places and am trying to figure out how to make it smaller ... copy paste-ish / inline.

@foreach(var m in Model.ObjectList)
{
 <td @if(m.RandomObject.isFlagged){
     <text>class="flagged"</text>
     }
 >
  @m.RandomObject.Name @m.RandomObject.Description
 </td>
}

Note that each ObjectList in different places has different RandomObjects.

I suppose this will work as well, but still seems like not the best practice:

<td class="flagged@(m.RandomObject.isFlagged)">...

and then the css definition will be .flaggedtrue

+5
source share
1 answer

I usually use a ? ternary operator for this kind of thing

<td class="@(m.RandomObject.isFlagged ? "flagged" : "")">
  ...
</td>
+7
source

All Articles