Search code examples
asp.net-mvcrazor

Writing conditional HTML with razor


Depending on my record, I'd like to change the style of the table row in my current iteration.

The below example doesn't work, but how would I go about doing this correctly?

 foreach (var item in Model)
                {
                    @{ 
                        if (item.DataState != DataState.Active)
                        {
                            <tr style="background-color: red">
                        }
                        else
                            <tr>
                    }
                    <td>@item.Name</td>
                  </tr>
                 }

So effectively, I'd like to dynamically render the <tr> element differently based on the DataState of my model.


Solution

  • Here's a shorter approach:

    @foreach (var item in Model)
    {
        <tr @(item.DataState != DataState.Active ? "style=background-color:red" : "")>
            <td>@item.Name</td>
        </tr>
    }