I want to add class to a <tr>
element depending on model's attribute:
<table> <tbody> @foreach (var item in Model) { if (item.Level == 1) { <tr class="classA"> } else if (item.Level == 2) { <tr class="classB"> } else { <tr> } <td>...</td> <td>...</td> </tr> </tbody> </table>
My IDE tells me my <tr>
element is not closed. How can I dynamically add the class value using razor?
I would use the ternary operator ? and write something like that.
<tr class="@(item.Level==1?"classA":item.Level == 2?"classB":"")">
It isn't very readable, and won't work with complex comparaisons. In these cases, I would suggest you to declare a method in the razor view
@functions{ public string GetClassFromLevel(int level) { return level == 1 ? "classA" : level == 2 ? "classB" : ""; } } <tr class"@GetClassFromLevel(item.Level)">
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