Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 480
Daniel Minnaar Avatar asked Nov 29 '22 01:11

Daniel Minnaar


2 Answers

Here's a shorter approach:

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

Edit: Code fixed

like image 78
Skuami Avatar answered Dec 10 '22 23:12

Skuami


There are multiple way you can write condition.

Option 1:

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

Option 2:

@foreach (var item in Model)
{
    <tr style="@( item.DataState != DataState.Active ? "background-color: red;" : "" )">
        <td>@item.Name</td>
    </tr>
}
like image 20
Sender Avatar answered Dec 10 '22 22:12

Sender