How to set html attributes like class using MVC Razor?

How to set html attributes using Razor?

In the code below, I would like to set the element class attribute if the "Succeeded" property of the current model is true.

<tbody> @foreach (CharlieTestRunViewModel charlieTestRunViewModel in Model) { <tr class="@if( !@charlieTestRunViewModel.Succeeded ){'trFailedTestRun'}"> <td> @charlieTestRunViewModel.Succeeded </td> </tr> } </tbody> 

But that will not work.

How to do it?

thanks

+4
source share
4 answers

How about using a conditional statement:

 <tr class="@(!charlieTestRunViewModel.Succeeded ? "trFailedTestRun" : "")"> 

If if:

 <tr class="@if( !@charlieTestRunViewModel.Succeeded ){<text>trFailedTestRun</text>}"> 
+5
source

I find using a razor helper the most elegant

 @helper ClassIf(bool condition, string className) { if (condition) { @className } } 

and use it like

  <tr class="@MyHelpers.ClassIf(charlieTestRunViewModel.Succeeded, "trFailedTestRun")"> 
+3
source

I would make an extension method for HtmlHelper as follows

 public static MvcHtmlString GetFailedClass(this HtmlHelper html, bool condition) { if(!condition) return MvcHtmlString.Create("trFailedTestRun") } 

And then in sight

 <tr class="@Html.GetFailedClass(charlieTestRunViewModel.Succeeded)"> 
0
source

You can use this

<tr class = "@ (Model.Succeeded?" trPassedTestRun ":" trFailedTestRun ")">

you must direct your model on top of your view as shown below

@model charlieTestRunViewModel

0
source

Source: https://habr.com/ru/post/1401183/


All Articles