Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Can I optimize the class assignment here at all? I have to do this in a lot of different places and am trying to figure out how to make it less...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 the different places has differnt RandomObjects.

I suppose this would work too, but still seems not best practice:

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

and then have the css definition be .flaggedtrue

like image 874
Travis J Avatar asked Mar 26 '12 00:03

Travis J


People also ask

Can you dynamically change CSS?

It is worth noting that while pre/postprocessor variables are only used at compilation-time, CSS variables can be used and updated dynamically.

Does Razor use CSS?

The styles defined in Example. razor. css are only applied to the rendered output of the Example component. CSS isolation is applied to HTML elements in the matching Razor file.

How do you add a Razor to CSS?

All you have to do is to place a style sheet in the Pages folder alongside the page that it is intended to affect. You just need to follow a specific naming convention, which is the Razor page file name with . css on the end. The bundled file itself is placed in the wwwroot folder when the application is published.


1 Answers

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

<td class="@(m.RandomObject.isFlagged ? "flagged" : "")">
  ...
</td>
like image 75
Andrew Avatar answered Nov 15 '22 06:11

Andrew