Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Statement (For CSS Class) on Razor Views

I need to switch between a CSS class depending if the message is read.

In simple it should be like this:

if (item.status == "Unread")
{
  <tr style="font-weight:bold">
  ...
}
else
{
  <tr>
  ...
}

I am having trouble achieving this though. Can something tell me a good to get this done? Should I be using a HTML helper or something?

This is the full code so far:

@foreach (var item in Model) {

    if (item.status == "Unread")
    {
        <tr style="font-weight:bold">
            <td>
                @Html.DisplayFor(modelItem => item.timestamp)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.subject)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.message_text)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.status)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.user_sender.username)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.user_reciever.username)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.id }) |
                @Html.ActionLink("Details", "Details", new { id = item.id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.id })
            </td>
        </tr>
    }
}
like image 723
JohnC1 Avatar asked Dec 07 '13 02:12

JohnC1


Video Answer


3 Answers

A simple solution would be something like this:

@foreach (var item in Model) 
{
    var style = (item.status == "Unread") ? "font-weight:bold" : "";

    <tr style="@style">
        ...
    </tr>
}

But note, it's generally cleaner to have a separate CSS class, then directly decorate the elements the appropriate class based on its status. For example:

/* css */
tr.status-unread { font-weight: bold; }
...

/* razor */
@foreach (var item in Model) 
{
    <tr class="[email protected]()">
        ...
    </tr>
}
like image 106
p.s.w.g Avatar answered Sep 28 '22 12:09

p.s.w.g


Another simpler solution would be this,

  1. With single condition:

    @foreach (var item in Model) 
    {
        <tr style="@Html.Raw(item.status == "Unread" ? "font-weight:bold" : "")">
            ...
        </tr>
    }
    
  2. OR you can set CSS class as you asked with multiple conditions if any,

    @foreach (var item in Model) 
    {
        <tr class="@Html.Raw((item.status == "Unread" && item.subject == "Hello World") ? "alert-success" : "")">
            ...
        </tr>
    }
    
like image 26
Adhik Avatar answered Sep 28 '22 12:09

Adhik


This way I used in my project.

You can use unitary operator like below

<td style="color:'@(item.ChangeRate > 0 ? "red" : "blue")'">
 <i class="fa" class="@(item.ChangeRate > 0 ? "fa-caret-up" : "fa-caret-down")"></i>
</td>
like image 30
Hien Nguyen Avatar answered Sep 28 '22 13:09

Hien Nguyen