Reputation: 27021
How to set html attributes using when Razor?
In the below code, I'd like to set the class attribute of element if "Succeeded" property of the current model is true.
<tbody>
@foreach (CharlieTestRunViewModel charlieTestRunViewModel in Model)
{
<tr class="@if([email protected]){'trFailedTestRun'}">
<td>
@charlieTestRunViewModel.Succeeded
</td>
</tr>
}
</tbody>
But it doesn't work.
How to achieve this?
Thanks
Upvotes: 5
Views: 4310
Reputation: 139818
What about using the conditional operator:
<tr class="@(!charlieTestRunViewModel.Succeeded ? "trFailedTestRun" : "")">
With if:
<tr class="@if([email protected]){<text>trFailedTestRun</text>}">
Upvotes: 5
Reputation: 351
You can use this
< tr class="@(Model.Succeeded ? "trPassedTestRun":"trFailedTestRun")" >
you have to refer you model on top of your View like below
@model charlieTestRunViewModel
Upvotes: 0
Reputation: 39501
I find using razor helper most elegant
@helper ClassIf(bool condition, string className)
{
if (condition)
{
@className
}
}
and use it like
<tr class="@MyHelpers.ClassIf(charlieTestRunViewModel.Succeeded, "trFailedTestRun")">
Upvotes: 3
Reputation: 937
I would make a Extension method to HtmlHelper like this
public static MvcHtmlString GetFailedClass(this HtmlHelper html, bool condition)
{
if(!condition)
return MvcHtmlString.Create("trFailedTestRun")
}
And then in view
<tr class="@Html.GetFailedClass(charlieTestRunViewModel.Succeeded)">
Upvotes: 0