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>
}
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.
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.