Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a class to html element dynamically using razor syntax?

Tags:

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?

like image 800
cameron Avatar asked Oct 29 '12 13:10

cameron


1 Answers

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)"> 
like image 94
Eilistraee Avatar answered Oct 19 '22 08:10

Eilistraee