1

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>
     }

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! This worked very well. Also, a small edit but it should be data-status='complete'. I was doing this wrong in the example I provided just FYI.
0

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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.