5

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

4 Answers 4

5

What about using the conditional operator:

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

With if:

<tr class="@if([email protected]){<text>trFailedTestRun</text>}">
Sign up to request clarification or add additional context in comments.

3 Comments

+1 But note it's the conditional operator. That's my preferred one anyway, expressive. But others will no doubt prefer an HtmlHelper extension.
@AndrasZoltan Good catch! I didn't know that I'm using the operator's name wrong :)
Well I'd like to say that I've never done it - but I would be lying. It doesn't help that it's the only ternary operator!
3

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")">

Comments

0

I would make a Extension method to HtmlHelper like this

public static MvcHtmlString GetFailedClass(this HtmlHelper html, bool condition)
    {
        if(!condition)
           return MvcHtmlString.Create("trFailedTestRun")
    }

And then in view

<tr class="@Html.GetFailedClass(charlieTestRunViewModel.Succeeded)">

Comments

0

You can use this

< tr class="@(Model.Succeeded ? "trPassedTestRun":"trFailedTestRun")" >

you have to refer you model on top of your View like below

@model charlieTestRunViewModel

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.