Reputation: 328
I'm trying to dynamically set an attribute(data-status) for a div if a condition is met.
I am currently using the @Html.Raw helper however it's not making its way in to the element.
I have also attempted to use Response.Write() however it just writes everything to the top of the page.
Is there a best way to actually embed this in to the code or maybe create/set a new attribute?
@foreach (var r in Model)
{
<div class="marker"
data-date="@r.date_finished"
data-name="@r.name"
@if (r.complete == "CP")
{
@Html.Raw("data-status='complete'");
}
>
</div>
}
Upvotes: 1
Views: 2079
Reputation: 56688
This should do it:
<div class="marker"
data-date="@r.date_finished"
data-name="@r.name"
@{if (r.complete == "CP") { <text>data-status='complete'</text> }}>
Notice the usage of <text>
tag. This is a special tag which Razor uses to output content as is.
Upvotes: 6
Reputation: 12295
When I run into this scenario I use a tertiary expression:
<div @(r.complete == "CP" ? "data-status='complete'" : "") >
If your logic is more complex you could also use a static helper method.
<div @r.RenderComplete() >
public static class RExtension{
public static string RenderComplete( this R r){
// logic here
}
}
Upvotes: 0