Search code examples
asp.net-mvcrazorif-statementforeach

MVC Razor, add if statement to foreach loop


I'm trying to add data from my model to a table with razor. My problem is that i want an if statement to decide what class the tagg should be and i can't get this to work.

When i add the if i get the following error when i run the code

The foreach block is missing a closing "}" character

How should i add the if statement? This is my current code

@{
      var counter = 0;            
}
@foreach (var item in Model)
{
       if(item.status == "Active") {
           <tr>
       }
       else {
           <tr class="danger">
       }
       <td>@counter</td>
       <td>@item.FirstName @item.LastName</td>
       <td>@item.Email</td>
       <td>@item.PhoneNumber</td>
       <td>Ändra</td>
       <td>Inaktivera</td>
        </tr>     
counter++;
}

Solution

  • MVC should detect html tags and render those out, however it seem this doesnt always work.

    In between the curly brackets, try adding a tag

    eg:

    {
    <text> 
       your html 
    </text>
    } 
    

    or

    if you just adding the class try something like:

    <tr @(item.status == "Active" ? String.Empty : "class=\"danger\"" )>