If Statement (for CSS class) in Razor view

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

In simple form, it should be like this:

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

I am having problems with this. Can anything tell me well to do this? Should I use an HTML helper or something else?

This is the full code:

 @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> } } 
+6
source share
2 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 that it is generally clean to have a separate CSS class, and then directly decorate elements with the corresponding class based on its status. For instance:

 /* css */ tr.status-unread { font-weight: bold; } ... /* razor */ @foreach (var item in Model) { <tr class=" status-@item.status.ToLowerInvariant ()"> ... </tr> } 
+22
source

Another simpler solution would be this,

  • Under one condition:

     @foreach (var item in Model) { <tr style="@Html.Raw(item.status == "Unread" ? "font-weight:bold" : "")"> ... </tr> } 
  • OR you can set the CSS class according to your request with several conditions, if any,

     @foreach (var item in Model) { <tr class="@Html.Raw((item.status == "Unread" && item.subject == "Hello World") ? "alert-success" : "")"> ... </tr> } 
0
source

All Articles