How to change the class of depending on its value in C # MVC

1

I have this form that gives me two data "active and deactivated, how to make them change depending on, with the class

class"label label-success y label-danger'

  <tbody>
        @foreach (var item in Model)
        {
          <tr>
              <td>
               @Html.DisplayFor(modelItem => item.PKOBJETO)
                      </td>
                              <td>
               @Html.DisplayFor(modelItem => item.ESTATUS)
                      </td>                                       
         }
</tbody>
    
asked by DC-Rom 27.09.2018 в 18:28
source

2 answers

0

What you could do would be to put a condition within your cycle and based on that add the class you need otherwise we can use a label since DisplayFor can not be added a class because it only plasma as such the content and LabelFor plasma the label with the content inside the tag

<tbody>
    @foreach (var item in Model) 
    {
     <tr>
        @if(item.ESTATUS=="Activo"){
        <td>
           @Html.LabelFor(model => item.PKOBJETO, htmlAttributes: new { @class = "label label-success" })
        </td>
        <td>
           @Html.LabelFor(model => item.ESTATUS, htmlAttributes: new { @class = "label label-success" })
        </td>
        }
        else {
        <td>
           @Html.LabelFor(model => item.PKOBJETO, htmlAttributes: new { @class = "label-danger" })
        </td>
        <td>
           @Html.LabelFor(model => item.ESTATUS, htmlAttributes: new { @class = "label-danger" })
        </td>
        }
     </tr>
     }
</tbody>
    
answered by 27.09.2018 / 18:56
source
0

Usually, in razor, the best option is to use the Ternary Operator

Taking as an example the classes estaActivo and estaDesactivado you could do it in the following way

<td class="@(item.ESTATUS=="Activo" ? "estaActivo" : "estaDesactivado")"> @Html.DisplayFor(x => x.PKOBJETO) </td>
    
answered by 27.09.2018 в 20:38