Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set html attributes such as class using MVC Razor?

How to set html attributes using when Razor?

In the below code, I'd like to set the class attribute of element if "Succeeded" property of the current model is true.

<tbody>
                @foreach (CharlieTestRunViewModel charlieTestRunViewModel in Model)
    {
                    <tr class="@if([email protected]){'trFailedTestRun'}">
                        <td>
                            @charlieTestRunViewModel.Succeeded
                        </td>
                                    </tr>
    }
            </tbody>

But it doesn't work.

How to achieve this?

Thanks

like image 918
The Light Avatar asked Mar 13 '12 14:03

The Light


2 Answers

What about using the conditional operator:

<tr class="@(!charlieTestRunViewModel.Succeeded ? "trFailedTestRun" : "")">

With if:

<tr class="@if([email protected]){<text>trFailedTestRun</text>}">
like image 99
nemesv Avatar answered Sep 27 '22 00:09

nemesv


I find using razor helper most elegant

@helper ClassIf(bool condition, string className)
{
   if (condition)
   {
      @className
   }    
}

and use it like

 <tr class="@MyHelpers.ClassIf(charlieTestRunViewModel.Succeeded, "trFailedTestRun")">
like image 40
archil Avatar answered Sep 24 '22 00:09

archil